-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCheckIfTheBinaryTreeIsHeight-BalancedOrNot.cpp
More file actions
67 lines (56 loc) · 1.47 KB
/
Copy pathCheckIfTheBinaryTreeIsHeight-BalancedOrNot.cpp
File metadata and controls
67 lines (56 loc) · 1.47 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Q119 https://leetcode.com/problems/balanced-binary-tree/submissions/
// Time: O(n)
class Solution {
public:
int dfsheight(TreeNode *root) {
if(!root) return 0;
int lh=dfsheight(root->left);
if(lh==-1) return -1;
int rh=dfsheight(root->right);
if(rh==-1) return -1;
if(abs(lh-rh)>1) return -1;
return max(lh,rh)+1;
}
bool isBalanced(TreeNode* root) {
return dfsheight(root)!=-1;
}
};
//Alternative of above code (Same approach and time complexity)
class Solution {
public:
int dfsheight(TreeNode *root) {
if(!root) return 0;
int lh=dfsheight(root->left);
int rh=dfsheight(root->right);
if(abs(lh-rh)>1) return -1;
if(lh==-1||rh==-1) return -1;
return max(lh,rh)+1;
}
bool isBalanced(TreeNode* root) {
return dfsheight(root)!=-1;
}
};
// Time: O(n*n)
class Solution {
public:
int height(TreeNode *root) {
if(root==NULL)
return 0;
return 1+ max(height(root->left),height(root->right));
}
bool isBalanced(TreeNode* root) {
if(root==NULL){
return true;
}
int lh=height(root->left);
int rh=height(root->right);
if((abs(lh-rh)>1)){
return false;
}
else{
if(!isBalanced(root->left)||!isBalanced(root->right))
return false;
}
return true;
}
};