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() {}
相关推荐
geobuilding10 分钟前
将大规模shp白模贴图转3dtiles倾斜摄影,并可单体化拾取建筑
算法·3d·智慧城市·数据可视化·贴图
jghhh0118 分钟前
基于高斯伪谱法的弹道优化方法及轨迹仿真计算
算法
ftpeak41 分钟前
《Rust+Slint:跨平台GUI应用》第八章 窗体
开发语言·ui·rust·slint
mm-q29152227292 小时前
【天野学院5期】 第5期易语言半内存辅助培训班,主讲游戏——手游:仙剑奇侠传4,端游:神魔大陆2
人工智能·算法·游戏
MoRanzhi12032 小时前
Python 实现:从数学模型到完整控制台版《2048》游戏
数据结构·python·算法·游戏·数学建模·矩阵·2048
2401_841495642 小时前
【数据结构】基于BF算法的树种病毒检测
java·数据结构·c++·python·算法·字符串·模式匹配
蒙奇D索大3 小时前
【算法】递归算法实战:汉诺塔问题详解与代码实现
c语言·考研·算法·面试·改行学it
一只鱼^_3 小时前
力扣第 474 场周赛
数据结构·算法·leetcode·贪心算法·逻辑回归·深度优先·启发式算法
叫我龙翔3 小时前
【数据结构】从零开始认识图论 --- 单源/多源最短路算法
数据结构·算法·图论
深圳佛手4 小时前
几种限流算法介绍和使用场景
网络·算法