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);
}
相关推荐
xxxxxmy2 分钟前
同向双指针(滑动窗口)
python·算法·滑动窗口·同向双指针
释怀°Believe9 分钟前
Daily算法刷题【面试经典150题-5️⃣图】
算法·面试·深度优先
List<String> error_P10 分钟前
数据结构:链表-单向链表篇
算法·链表
ss27316 分钟前
ConcurrentHashMap:扩容机制与size()方法
算法·哈希算法
2401_8603195222 分钟前
在React Native鸿蒙跨平台开发中实现一个冒泡排序算法并将其应用于数据排序,如何进行复制数组以避免直接修改状态中的数组
javascript·算法·react native·react.js·harmonyos
im_AMBER24 分钟前
Leetcode 72 数组列表中的最大距离
c++·笔记·学习·算法·leetcode
编程饭碗39 分钟前
【Java循环】
java·服务器·算法
曾几何时`1 小时前
归并排序(一)
数据结构·算法·leetcode
Dream it possible!1 小时前
LeetCode 面试经典 150_图的广度优先搜索_最小基因变化(93_433_C++_中等)(广度优先搜索(BFS))
c++·leetcode·面试·广度优先
CoovallyAIHub2 小时前
何必先OCR再LLM?视觉语言模型直接读图,让百页长文档信息不丢失
深度学习·算法·计算机视觉