leetcode简单题24 N.111 二叉树的最小深度 rust描述

rust 复制代码
// [3,9,20,null,null,15,7] 2
// [2,null,3,null,4,null,5,null,6] 5
use std::rc::Rc;
use std::cell::RefCell;
// Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
  pub val: i32,
  pub left: Option<Rc<RefCell<TreeNode>>>,
  pub right: Option<Rc<RefCell<TreeNode>>>,
}

impl TreeNode {
  #[inline]
  pub fn new(val: i32) -> Self {
    TreeNode {
      val,
      left: None,
      right: None
    }
  }
}
// dfs
pub fn min_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
    fn min_depth_helper(node: &Option<Rc<RefCell<TreeNode>>>) -> i32 {
        match node {
            Some(node) => {
                let left_depth = min_depth_helper(&node.borrow().left);
                let right_depth = min_depth_helper(&node.borrow().right);
                if left_depth == 0 || right_depth == 0 {
                    return left_depth + right_depth + 1;
                }
                left_depth.min(right_depth) + 1
            }
            None => 0,
        }
    }

    min_depth_helper(&root)
}
use std::collections::VecDeque;
// bfs
pub fn min_depth2(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
    if root.is_none() {
        return 0;
    }

    let mut queue = VecDeque::new();
    queue.push_back((root, 1));

    while let Some((node, depth)) = queue.pop_front() {
        if let Some(node) = node {
            let node = node.borrow();
            if node.left.is_none() && node.right.is_none() {
                return depth;
            }
            if node.left.is_some() {
                queue.push_back((node.left.clone(), depth + 1));
            }
            if node.right.is_some() {
                queue.push_back((node.right.clone(), depth + 1));
            }
        }
    }

    0
}
fn main() {}
相关推荐
geats人山人海2 小时前
数据结构第六章c语言 树的存储下二叉树的概念和存储
c语言·数据结构·算法
爱吃牛肉的大老虎2 小时前
Rust对象之结构体,枚举,特性
开发语言·后端·rust
漂流瓶jz2 小时前
UVA-12627 奇怪的气球膨胀 题解答案代码 算法竞赛入门经典第二版
算法·图论·递归·aoapc·算法竞赛入门经典·uva·12627
jarvisuni2 小时前
DeepSeekFlash前端依旧拉垮,而且变慢了很多!
前端·javascript·算法
kobesdu3 小时前
流形上的优化:SO(3)与SE(3)的广义加减法在FAST-LIO中如何简化状态估计
人工智能·算法·fastlio
白狐_7983 小时前
408 数据结构算法题 01:线性表暴力求解保分指南
java·数据结构·算法
乐观勇敢坚强的老彭3 小时前
C++信奥:开关门、开关灯问题
开发语言·c++·算法
冻柠檬飞冰走茶3 小时前
PTA基础编程题目集 7-31 字符串循环左移(C语言实现)
c语言·开发语言·数据结构·算法
Hi李耶3 小时前
【LeetCode】4-寻找两个正序数组的中位数
算法·leetcode·职场和发展
图灵机z4 小时前
【算法提高课】AcWing 1027. 方格取数 长期攻克提高课-day3(3/219)
算法