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 分钟前
mebdlts3.4.1安全启动全流程
服务器·算法
Nebula_g8 分钟前
JavaSE拓展:可变参数
java·开发语言·算法·安全·javase·可变参数
129Lab28 分钟前
BMS 核心算法:SOC 估算从安时积分到 LSTM-UKF 串级融合的 30 年演进(附 Python 实现)
python·算法·lstm·python3.11·bms·soc估算
kgkg29 分钟前
我通过逆向学到了douyin的美颜算法
算法
Xin77031 分钟前
LeetCode 230. 二叉搜索树中第 K 小的元素(迭代中序遍历 + 栈)
leetcode
anew___1 小时前
《从零手写操作系统 (30):环境变量与进程上下文——export/unset与继承语义》
java·开发语言·网络·jvm·算法
垆边人似月.1 小时前
城市连通性(200分 / 并查集)
数据结构·算法·图论
Gust of wind1 小时前
串与KMP模式匹配:存储结构、基本操作、next数组手算
c语言·数据结构·后端·算法
Navigator_Z1 小时前
LeetCode //C - 1283. Find the Smallest Divisor Given a Threshold
c语言·算法·leetcode
啦啦啦啦啦zzzz2 小时前
一致性哈希
服务器·算法·哈希算法·c++20·分布式存储