Skip to content

Commit f4826dd

Browse files
authored
Merge pull request neetcode-gh#2650 from rmrt1n/110
Create 0110-balanced-binary-tree.rs
2 parents 8673546 + 2c70693 commit f4826dd

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

rust/0110-balanced-binary-tree.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
use std::rc::Rc;
2+
use std::cell::RefCell;
3+
impl Solution {
4+
pub fn is_balanced(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
5+
fn dfs(root: Option<Rc<RefCell<TreeNode>>>) -> (bool, i32) {
6+
match root {
7+
None => (true, 0),
8+
Some(node) => {
9+
let (l_balanced, l_max) = dfs(node.borrow().left.clone());
10+
let (r_balanced, r_max) = dfs(node.borrow().right.clone());
11+
let balanced = l_balanced && r_balanced && (l_max - r_max).abs() <= 1;
12+
(balanced, 1 + l_max.max(r_max))
13+
}
14+
}
15+
}
16+
17+
dfs(root).0
18+
}
19+
}

0 commit comments

Comments
 (0)