-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCheck for Balanced Tree.cpp
42 lines (36 loc) · 1.07 KB
/
Check for Balanced Tree.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
39
40
41
42
Given a binary tree, find if it is height balanced or not.
A tree is height balanced if difference between heights of left and right subtrees is not more than one for all nodes of tree.
link-- > https://practice.geeksforgeeks.org/problems/check-for-balanced-tree/1
solution-- >
class solution{
pair<bool, int> solve(Node *root)
{
if (root == NULL)
{
pair<bool, int> p = make_pair(true, 0);
return p;
}
pair<bool, int> left = solve(root->left);
pair<bool, int> right = solve(root->right);
bool leftt = left.first;
bool rightt = right.first;
int heightleft = left.second;
int heightright = right.second;
bool ans = abs(heightleft - heightright) <= 1;
pair<bool, int> pr;
if (leftt && rightt && ans)
{
pr.first = true;
}
pr.second = max(heightleft, heightright) + 1;
return pr;
}
public:
// Function to check whether a binary tree is balanced or not.
bool isBalanced(Node *root)
{
if (root == NULL)
return true;
return solve(root).first;
}
};