leetcode简单题21 N.104 二叉树的最大深度 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);
}

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-13 00:02:02       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-13 00:02:02       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-13 00:02:02       57 阅读
  4. Python语言-面向对象

    2024-07-13 00:02:02       68 阅读

热门阅读

  1. wifi中的PSR技术

    2024-07-13 00:02:02       20 阅读
  2. mac ssh连接工具

    2024-07-13 00:02:02       25 阅读
  3. android inflate 参数含义

    2024-07-13 00:02:02       18 阅读
  4. React@16.x(56)Redux@4.x(5)- 实现 createStore

    2024-07-13 00:02:02       21 阅读
  5. leetcode热题100.零钱兑换(动态规划)

    2024-07-13 00:02:02       18 阅读
  6. 跟我从零开始学STL(STL代码基础02)---vector容器

    2024-07-13 00:02:02       18 阅读
  7. 数据结构第18节 散列表 - 应用

    2024-07-13 00:02:02       21 阅读