精華區beta Marginalman 關於我們 聯絡資訊
用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; } }; 這到底什麼語言 我落淚了 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 60.248.143.163 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1689324430.A.F5F.html
Rushia: 這沒法再簡化了喔 07/14 17:04
Che31128: rust:00 07/14 17:06