-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleet110.cpp
More file actions
46 lines (45 loc) · 979 Bytes
/
Copy pathleet110.cpp
File metadata and controls
46 lines (45 loc) · 979 Bytes
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(root == NULL)
return true ;
return dfs(root) ;
}
bool dfs(TreeNode* x){
x->val = 0 ;
int lh, rh ;
if(x->left == NULL){
lh = 0;
}else {
if (!dfs(x->left)){
return false ;
}
lh = x->left->val ;
}
if(x->right == NULL){
rh = 0 ;
}else {
if (!dfs(x->right)){
return false ;
}
rh = x->right->val ;
}
if(lh-rh<-1 || lh-rh>1){
return false ;
}
if(lh>rh)
x->val = lh+1 ;
else
x->val = rh+1 ;
return true ;
}
};