Re: [闲聊] 每日LeetCode

楼主: yam276 ('_')   2023-07-14 16:47:08
用Easy来玩Rust
104. Maximum Depth of Binary Tree
Given the root of a binary tree, return its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest path
from the root node down to the farthest leaf node.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: 3
Example 2:
Input: root = [1,null,2]
Output: 2
Constraints:
The number of nodes in the tree is in the range [0, 104].
-100 <= Node.val <= 100
Code:
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn max_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
match root {
Some(node) =>{
let mut node = node.borrow_mut();
let left_depth = Self::max_depth(node.left.clone());
let right_depth = Self::max_depth(node.right.clone());
return std::cmp::max(left_depth, right_depth) + 1;
}
None => return 0,
}
return 0;
}
}
等价于:
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == nullptr)
return 0;
int right_depth = maxDepth(root->right);
int left_depth = maxDepth(root->left);
return max(right_depth, left_depth) + 1;
}
};
这到底什么语言 我落泪了
作者: Rushia (みけねこ的鼻屎)   2023-07-14 17:04:00
这没法再简化了喔
作者: Che31128 (justjoke)   2023-07-14 17:06:00
rust:00

Links booklink

Contact Us: admin [ a t ] ucptt.com