Update 0110.平衡二叉树.md

This commit is contained in:
fw_qaq
2022-11-15 21:58:16 +08:00
committed by GitHub
parent 6d75b123f5
commit 1af721e1ed

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">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>