-
Notifications
You must be signed in to change notification settings - Fork 0
/
balanced_binary_tree.c++
50 lines (48 loc) · 1.31 KB
/
balanced_binary_tree.c++
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
/**
* 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:
// ek baar right jao ek baar left uar maximum depth nikalo aur
// difference check kar lo
void mxidep(TreeNode*root, int n , int&ans){
if (root == NULL) return; // Check for null
if (root->right == NULL && root->left == NULL) {
n++;
ans = max(n, ans);
n--;
return;
}
if(root->left){
mxidep(root->left,n+1,ans);
}
if(root->right){
mxidep(root->right,n+1,ans);
}
}
bool solve(TreeNode*root){
if(root==NULL){
return true;
}
int ans1=0;
int ans2=0;
mxidep(root->left,0,ans1);
mxidep(root->right,0,ans2);
if(abs(ans1-ans2)>1){
return false;
}else{
return solve(root->left) && solve(root->right);
}
}
bool isBalanced(TreeNode* root) {
return solve(root);
}
};