首页 > 其他分享 >leetcode简单题21 N.104 二叉树的最大深度 rust描述

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

时间:2024-07-12 22:55:55浏览次数:11  
标签:node right N.104 Some let 二叉树 new leetcode left


 

// [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);
}

标签:node,right,N.104,Some,let,二叉树,new,leetcode,left
From: https://blog.csdn.net/BECOMEviolet/article/details/140364812

相关文章

  • LeetCode - #93 复原 IP 地址
    文章目录前言1.描述2.示例3.答案关于我们前言本题由于没有合适答案为以往遗留问题,最近有时间将以往遗留问题一一完善。我们社区陆续会将顾毅(Netflix增长黑客,《iOS面试之道》作者,ACE职业健身教练。)的Swift算法题题解整理为文字版以方便大家学习与阅读。......
  • LeetCode 2974. 最小数字游戏(排序)
    题目:2974.最小数字游戏思路:排序后,两个两个取出来进行操作即可classSolution{public:vector<int>numberGame(vector<int>&nums){sort(nums.begin(),nums.end());vector<int>v;for(inti=1;i<nums.size();i+=2){v.pu......
  • 代码随想录算法训练营Day22 | Leetcode 77. 组合 | 216.组合总和III | 17.电话号码的
    今日任务77.组合题目链接:https://leetcode.cn/problems/combinations/description/题目描述:CodeclassSolution{vector<vector<int>>ans;vector<int>path;public:vector<vector<int>>combine(intn,intk){//intst......
  • 【初阶数据结构】树与二叉树:从零开始的奇幻之旅
    初阶数据结构相关知识点可以通过点击以下链接进行学习一起加油!时间与空间复杂度的深度剖析深入解析顺序表:探索底层逻辑深入解析单链表:探索底层逻辑深入解析带头双向循环链表:探索底层逻辑深入解析栈:探索底层逻辑深入解析队列:探索底层逻辑深入解析循环队列:探索底层逻辑......
  • 队列+二叉树广度优先
    题目出自力扣-n叉树的层序遍历我是原始人,递归写出一道题就只有递归思路,开始的想法是写深搜函数,传一个随着层数递增的int参数q,节点空就return,否则遍历所有节点,每个子节点又以q+1为层数递归,然后收集每一层的val即可代码;/*//DefinitionforaNode.classNode{public......
  • LeetCode 2950. 可整除子串的数量
    2950.可整除子串的数量每个英文字母都被映射到一个数字,如下所示。如果字符串的字符的映射值的总和可以被字符串的长度整除,则该字符串是 可整除 的。给定一个字符串 s,请返回 s 的 可整除子串 的数量。子串 是字符串内的一个连续的非空字符序列。示例1:Substrin......
  • 代码随想录算法训练营第六天 | Python | LeetCode242.有效的字母异位词、LeetCode349.
    哈希表理论https://programmercarl.com/%E5%93%88%E5%B8%8C%E8%A1%A8%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80.html一般哈希表都是用来快速判断一个元素是否出现集合里。数组/set/mapLeetCode242.有效的字母异位词题目链接:https://leetcode.cn/problems/valid-anagr......
  • 代码随想录算法训练营第四天 | Python | LeetCode24.两两交换链表中的节点、19.删除链
    LeetCode24.两两交换链表中的节点题目链接:https://leetcode.cn/problems/swap-nodes-in-pairs/description/文章/视频链接:https://programmercarl.com/0024.%E4%B8%A4%E4%B8%A4%E4%BA%A4%E6%8D%A2%E9%93%BE%E8%A1%A8%E4%B8%AD%E7%9A%84%E8%8A%82%E7%82%B9.html#%E7%AE%9......
  • 【完结】LeetCode 热题 HOT 100分类+题解+代码详尽指南
    目录LeetCode热题100前言LeetcodeTop100题目和答案-哈希LeetcodeTop100题目和答案-双指针篇LeetcodeTop100题目和答案-滑动窗口篇LeetcodeTop100题目和答案-子串篇LeetcodeTop100题目和答案-普通数组篇LeetcodeTop100题目和答案-矩阵篇LeetcodeTop100题目和......
  • LeetCode --- 2103. Rings and Rods 解题报告
    Question:Thereare n ringsandeachringiseitherred,green,orblue.Theringsaredistributed acrosstenrods labeledfrom 0 to 9.Youaregivenastring rings oflength 2n thatdescribesthe n ringsthatareplacedontotherods.Everyt......