forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0110-balanced-binary-tree.cpp
47 lines (41 loc) · 1.14 KB
/
0110-balanced-binary-tree.cpp
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
/*
Given binary tree, determine if height-balanced (all left & right subtrees height diff <= 1)
Check if subtrees are balanced, if so, use their heights to determine further balance
Time: O(n)
Space: O(n)
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
int height = 0;
return dfs(root, height);
}
private:
bool dfs(TreeNode* root, int& height) {
if (root == NULL) {
height = -1;
return true;
}
int left = 0;
int right = 0;
if (!dfs(root->left, left) || !dfs(root->right, right)) {
return false;
}
if (abs(left - right) > 1) {
return false;
}
height = 1 + max(left, right);
return true;
}
};