forked from iphkwan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Balanced_Binary_Tree.cc
39 lines (39 loc) · 1.06 KB
/
Balanced_Binary_Tree.cc
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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool judge(TreeNode *root, int &depth) {
if (root == NULL) {
depth = 0;
return true;
}
int leftHeight, rightHeight;
if (judge(root->left, leftHeight) && judge(root->right, rightHeight)) {
if (leftHeight > rightHeight + 1 || rightHeight > leftHeight + 1)
return false;
if (leftHeight > rightHeight) {
depth = leftHeight + 1;
} else {
depth = rightHeight + 1;
}
return true;
}
return false;
}
bool isBalanced(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (root == NULL) {
return true;
}
int tmp = 0;
return judge(root, tmp);
}
};