-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbalancedTree.cpp
38 lines (31 loc) · 943 Bytes
/
balancedTree.cpp
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
class Solution{
public:
//Function to check whether a binary tree is balanced or not.
pair<bool, int> isBalancedFast(Node* root) {
// base case
if(root == NULL)
{
pair<bool, int> p = make_pair(true, 0);
return p;
}
pair<int,int> left = isBalancedFast(root->left);
pair<int,int> right = isBalancedFast(root->right);
bool leftAns = left.first;
bool rightAns = right.first;
bool diff = abs (left.second - right.second ) <=1;
pair<bool,int> ans;
ans.second = max(left.second, right.second) + 1;
if(leftAns && rightAns && diff) {
ans.first = true;
}
else
{
ans.first = false;
}
return ans;
}
bool isBalanced(Node *root)
{
return isBalancedFast(root).first;
}
};