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() {}
相关推荐
智驱力人工智能7 小时前
工厂智慧设备检测:多模态算法提升工业安全阈值
人工智能·算法·安全·边缘计算·智慧工厂·智能巡航·工厂设备检测
茴香豆的茴18 小时前
转码刷 LeetCode 笔记[2]:203. 移除链表元素(python)
笔记·leetcode·链表
2501_9247314710 小时前
城市路口识别准确率↑31%!陌讯时空建模算法在交通拥堵识别中的突破
人工智能·算法·目标检测·计算机视觉·目标跟踪
熬了夜的程序员10 小时前
【华为机试】208. 实现 Trie (前缀树)
数据结构·算法·华为od·华为
小O的算法实验室12 小时前
2024年ESWA SCI1区TOP,自适应种群分配和变异选择差分进化算法iDE-APAMS,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
不吃洋葱.13 小时前
左子树之和
算法
金融小师妹14 小时前
基于AI量化模型的比特币周期重构:传统四年规律是否被算法因子打破?
大数据·人工智能·算法
数据智能老司机15 小时前
图算法趣味学——最短路径
数据结构·算法·云计算
快去睡觉~15 小时前
力扣109:有序链表转换二叉搜索树
算法·leetcode·链表
是Dream呀15 小时前
YOLOv8深度解析:从架构革新到应用实践
人工智能·算法