Merge pull request #1757 from Jack-Zhang-1314/patch-18

Update 0110.平衡二叉树.md about rust
This commit is contained in:
程序员Carl
2022-12-01 11:32:17 +08:00
committed by GitHub

View File

@ -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<Rc<RefCell<TreeNode>>>) -> bool {
Self::get_depth(root) != -1
}
pub fn get_depth(root: Option<Rc<RefCell<TreeNode>>>) -> 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)
}
}
```
<p align="center"> <p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank"> <a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/> <img src="../pics/网站星球宣传海报.jpg" width="1000"/>