-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbalanced_binary_tree.rs
More file actions
85 lines (75 loc) · 2.08 KB
/
balanced_binary_tree.rs
File metadata and controls
85 lines (75 loc) · 2.08 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
///
/// Problem: Balanced Binary Tree
///
/// Given a binary tree, determine if it is height-balanced.
///
/// A height-balanced binary tree is defined as a binary tree in which the depth of the
/// two subtrees of every node never differ by more than 1.
///
/// Example 1:
/// Input: root = [3,9,20,null,null,15,7]
/// Output: true
///
/// Example 2:
/// Input: root = [1,2,2,3,3,null,null,4,4]
/// Output: false
///
/// Example 3:
/// Input: root = []
/// Output: true
///
/// Constraints:
/// The number of nodes in the tree is in the range [0, 5000].
/// -10^4 <= Node.val <= 10^4
///
// Definition for a binary tree node (provided by LeetCode)
// #[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
// }
// }
// }
// # Solution:
// Time complexity: O(n²)
// Space complexity: O(n)
use std::rc::Rc;
use std::cell::RefCell;
use std::cmp;
impl Solution {
pub fn is_balanced(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
if root.is_none() {
return true;
}
let node = root.unwrap();
let node_ref = node.borrow();
// Get heights of left and right subtrees
let left_height = Self::height(node_ref.left.clone());
let right_height = Self::height(node_ref.right.clone());
// Check if current node is balanced and recursively check children
(left_height - right_height).abs() <= 1
&& Self::is_balanced(node_ref.left.clone())
&& Self::is_balanced(node_ref.right.clone())
}
fn height(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
if root.is_none() {
return 0;
}
let node = root.unwrap();
let node_ref = node.borrow();
1 + cmp::max(
Self::height(node_ref.left.clone()),
Self::height(node_ref.right.clone())
)
}
}