diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index 6e7c8c53..9751f2dd 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -810,6 +810,38 @@ func getHeight(_ root: TreeNode?) -> Int { } ``` +### rust + +递归 + +```rust +use std::cell::RefCell; +use std::rc::Rc; +impl Solution { + pub fn is_balanced(root: Option>>) -> bool { + Self::get_depth(root) != -1 + } + pub fn get_depth(root: Option>>) -> i32 { + if root.is_none() { + return 0; + } + let right = Self::get_depth(root.as_ref().unwrap().borrow().left.clone()); + let left = Self::get_depth(root.unwrap().borrow().right.clone()); + if right == -1 { + return -1; + } + if left == -1 { + return -1; + } + if (right - left).abs() > 1 { + return -1; + } + + 1 + right.max(left) + } +} +``` +