[闲聊] 每日leetcode 75 - Day15

楼主: yam276 ('_')   2025-06-19 15:01:32
104. Maximum Depth of Binary Tree
题目:
取得树的深度
思路:
Rust 解树的题目似乎都是用 Rc 包 RefCell
因为 Box 是唯一拥有者 所以当你访问的时候会消耗所有权
这样会破坏树的结构
所以通常都用多所有权与动态借用的 Option<Rc<RefCell<TreeNode>>
当你对 Rc 进行 .clone() 的时候也不会复制资料
而只是复制指标 也会省资源
那这题目 dfs 用递回是最快的
走左走右 每次回传 1 + 下一层次数
比较左右回来哪个大就选谁
Code:
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn max_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
match root {
None => 0,
Some(node) => {
let left_depth =
Solution::max_depth(node.borrow().left.clone());
let right_depth =
Solution::max_depth(node.borrow().right.clone());
1 + left_depth.max(right_depth)
}
}
}
}
作者: oin1104 (是oin的说)   2025-06-19 15:30:00
大师

Links booklink

Contact Us: admin [ a t ] ucptt.com