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);
}
相关推荐
CCF_NOI.7 分钟前
(普及−)B3629 吃冰棍——二分/模拟
数据结构·c++·算法
运器1231 小时前
【一起来学AI大模型】支持向量机(SVM):核心算法深度解析
大数据·人工智能·算法·机器学习·支持向量机·ai·ai编程
Zedthm1 小时前
LeetCode1004. 最大连续1的个数 III
java·算法·leetcode
神的孩子都在歌唱1 小时前
3423. 循环数组中相邻元素的最大差值 — day97
java·数据结构·算法
YuTaoShao1 小时前
【LeetCode 热题 100】73. 矩阵置零——(解法一)空间复杂度 O(M + N)
算法·leetcode·矩阵
dying_man2 小时前
LeetCode--42.接雨水
算法·leetcode
vortex53 小时前
算法设计与分析 知识总结
算法
艾莉丝努力练剑3 小时前
【C语言】学习过程教训与经验杂谈:思想准备、知识回顾(三)
c语言·开发语言·数据结构·学习·算法
ZZZS05163 小时前
stack栈练习
c++·笔记·学习·算法·动态规划
黑听人3 小时前
【力扣 困难 C】115. 不同的子序列
c语言·leetcode