-
Notifications
You must be signed in to change notification settings - Fork 0
/
Check if all leaves are at same level.cpp
142 lines (121 loc) · 2.8 KB
/
Check if all leaves are at same level.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
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
// THREE APPROACHES
/* Method - 1
BFS
Time complexity - O(N)
Space complexity- O(N)
*/
class Solution{
public:
bool check(Node *root)
{
queue<Node*> q;
q.push(root);
bool flag=0;
while(!q.empty())
{
if(flag)
return 0;
int size=q.size();
for(int i=0;i<size;i++)
{
Node* node=q.front();
q.pop();
if(node->left==NULL and node->right==NULL)
{
flag=1;
continue;
}
if(node->left)
{
if(flag)
return 0;
q.push(node->left);
}
if(node->right)
{
if(flag)
return 0;
q.push(node->right);
}
}
}
return 1;
}
};
/* Method - 2
DFS
Time complexity - O(N)
Space complexity- O(Height of tree)
*/
typedef pair<int,int> pi;
class Solution{
public:
pi help(Node* root)
{
//base case
if(!root)
return {0,0};
if(root->left==NULL and root->right==NULL)
return {1,1};
//recursive calls
//and small calculation
pi left,right;
left={-1e9,1e9};
right={-1e9,1e9};
if(root->left)
left=help(root->left);
if(root->right)
right=help(root->right);
return {max(left.first,right.first)+1,min(left.second,right.second)+1};
}
bool check(Node *root)
{
pi ans=help(root);
return ans.first==ans.second;
}
};
/* Method - 3
DFS
Time complexity - O(N)
Space complexity- O(Height of tree)
*/
typedef pair<int,int> pi;
class Solution{
public:
int help(Node* root,int& ans)
{
//base case
if(!root)
return 0;
if(root->left==NULL and root->right==NULL)
return 1;
//recursive calls
//and small calculation
int left,right;
left=right=0;
if(root->left)
{
left=help(root->left,ans);
if(!ans)
return 1;
}
if(root->right)
{
right=help(root->right,ans);
if(!ans)
return 1;
}
if(left!=0 and right!=0 and left!=right)
{
ans=0;
return 1;
}
return max(left,right)+1;
}
bool check(Node *root)
{
int ans=1;
int call=help(root,ans);
return ans;
}
};