-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path110. Balanced Binary Tree.cpp
More file actions
43 lines (38 loc) · 976 Bytes
/
110. Balanced Binary Tree.cpp
File metadata and controls
43 lines (38 loc) · 976 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
/**
* 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 ans;
bool isBalanced(TreeNode* root) {
ans = true;
int temp = checkbalance(root);
return ans;
}
int checkbalance(TreeNode* root)
{
if(!root)
{
return 0;
}
if(!ans)
{
return 0;
}
int leftsubtree = checkbalance(root->left);
int rightsubtree = checkbalance(root->right);
if(abs(leftsubtree-rightsubtree) > 1)
{
ans = false;
}
return 1+ max(leftsubtree,rightsubtree);
}
};