-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path110. Balanced Binary Tree
42 lines (33 loc) · 1002 Bytes
/
110. Balanced Binary Tree
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
/**
* 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:
pair<int, bool> solve(TreeNode* root)
{
if(root == NULL)
{
return {0, true};
}
pair<int, bool> left = solve(root -> left);
pair<int, bool> right = solve(root -> right);
pair<int, bool> ans;
//finding the height of that subtree
ans.first = max(left.first, right.first) + 1;
//checking for balanced
bool diff = abs(left.first - right.first) <= 1;
ans.second = left.second && right.second && diff;
return ans;
}
bool isBalanced(TreeNode* root) {
return solve(root).second;
}
};