-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBalanced Binary Tree.cpp
More file actions
63 lines (47 loc) · 1007 Bytes
/
Balanced Binary Tree.cpp
File metadata and controls
63 lines (47 loc) · 1007 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class ans{
public :
bool smallans;
int height;
ans()
{
smallans=true ;
height =0;
}
};
ans find_ans(TreeNode *root)
{
if(root==NULL)
return ans() ;
ans leftans= find_ans(root->left) ;
ans rightans=find_ans(root->right);
if(leftans.smallans==false||rightans.smallans==false)
{
return leftans ;
}
if(abs(leftans.height-rightans.height)<=1)
{
ans temp;
temp.height=1+max(leftans.height,rightans.height) ;
temp.smallans=true ;
return temp;
}
leftans.smallans=false ;
rightans.smallans=false ;
return leftans ;
}
int Solution::isBalanced(TreeNode* root) {
if(root==NULL)
return 0 ;
if(find_ans(root).smallans)
return 1;
return 0;
}