-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbalanced-binary-tree.rs
66 lines (52 loc) · 1.48 KB
/
balanced-binary-tree.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#![allow(dead_code, unused, unused_variables)]
fn main() {}
struct Solution;
// Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
left: None,
right: None,
}
}
}
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn is_balanced(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
if root.is_none() {
return true;
}
let root = root.unwrap();
let r1 = Rc::clone(&root);
let r2 = Rc::clone(&root);
let (x1, t1) = Self::height(RefCell::borrow_mut(&r1).left.take());
let (x2, t2) = Self::height(RefCell::borrow_mut(&r2).right.take());
t1 && t2 && (x1 - x2).abs() <= 1
}
fn height(root: Option<Rc<RefCell<TreeNode>>>) -> (i32, bool) {
if root.is_none() {
return (0, true);
}
let root = root.unwrap();
let r1 = Rc::clone(&root);
let r2 = Rc::clone(&root);
let (x1, t1) = Self::height(RefCell::borrow_mut(&r1).left.take());
if !t1 {
return (0, false);
}
let (x2, t2) = Self::height(RefCell::borrow_mut(&r2).right.take());
if !t2 {
return (0, false);
}
(x1.max(x2) + 1, (x1 - x2).abs() <= 1)
}
}