leetcode简单题21 N.104 二叉树的最大深度 rust描述

rust 复制代码
// [3,9,20,null,null,15,7] 3
// [1,null,2] 2
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,
        }
    }
}
// 递归
pub fn max_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
    fn dfs(node: &Option<Rc<RefCell<TreeNode>>>) -> i32 {
        if let Some(node) = node {
            let left_depth = dfs(&node.borrow().left);
            let right_depth = dfs(&node.borrow().right);
            return 1 + left_depth.max(right_depth);
        }
        0
    }
    dfs(&root)
}
use std::collections::VecDeque;
// 迭代
pub fn max_depth2(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
        if root.is_none() {
            return 0;
        }

        let mut queue = VecDeque::new();
        queue.push_back(root);
        let mut depth = 0;

        while !queue.is_empty() {
            let level_size = queue.len();
            for _ in 0..level_size {
                if let Some(Some(node)) = queue.pop_front() {
                    let node = node.borrow();
                    if let Some(left) = node.left.clone() {
                        queue.push_back(Some(left));
                    }
                    if let Some(right) = node.right.clone() {
                        queue.push_back(Some(right));
                    }
                }
            }
            depth += 1;
        }
        depth
}


fn main() {
    // 根据 [3,9,20,null,null,15,7] 3 编写测试用例
    let root = Some(Rc::new(RefCell::new(TreeNode {
        val: 3,
        left: Some(Rc::new(RefCell::new(TreeNode::new(9)))),
        right: Some(Rc::new(RefCell::new(TreeNode {
            val: 20,
            left: Some(Rc::new(RefCell::new(TreeNode::new(15)))),
            right: Some(Rc::new(RefCell::new(TreeNode::new(7)))),
        }))),
    })));
    assert_eq!(max_depth(root.clone()), 3);
    assert_eq!(max_depth2(root.clone()), 3);
}
相关推荐
程序猿进阶2 小时前
如何在 Visual Studio Code 中反编译具有正确行号的 Java 类?
java·ide·vscode·算法·面试·职场和发展·架构
Eloudy2 小时前
一个编写最快,运行很慢的 cuda gemm kernel, 占位 kernel
算法
程序猿练习生2 小时前
C++速通LeetCode中等第5题-无重复字符的最长字串
开发语言·c++·leetcode
king_machine design2 小时前
matlab中如何进行强制类型转换
数据结构·算法·matlab
西北大程序猿2 小时前
C++ (进阶) ─── 多态
算法
无名之逆2 小时前
云原生(Cloud Native)
开发语言·c++·算法·云原生·面试·职场和发展·大学期末
头发尚存的猿小二2 小时前
树——数据结构
数据结构·算法
好蛊2 小时前
第 2 课 春晓——cout 语句
c++·算法
山顶夕景2 小时前
【Leetcode152】分割回文串(回溯 | 递归)
算法·深度优先·回溯
许野平3 小时前
Rust:Result 和 Error
开发语言·后端·rust·error·result