-
Notifications
You must be signed in to change notification settings - Fork 0
/
Check whether BST contains Dead End.cpp
157 lines (126 loc) · 2.79 KB
/
Check whether BST contains Dead End.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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
//{ Driver Code Starts
//Initial template for C++
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node *left;
struct Node *right;
Node(int x){
data = x;
left = NULL;
right = NULL;
}
};
void insert(Node ** tree, int val)
{
Node *temp = NULL;
if(!(*tree))
{
temp = new Node(val);
*tree = temp;
return;
}
if(val < (*tree)->data)
{
insert(&(*tree)->left, val);
}
else if(val > (*tree)->data)
{
insert(&(*tree)->right, val);
}
}
int getCountOfNode(Node *root, int l, int h)
{
if (!root) return 0;
if (root->data == h && root->data == l)
return 1;
if (root->data <= h && root->data >= l)
return 1 + getCountOfNode(root->left, l, h) +
getCountOfNode(root->right, l, h);
else if (root->data < l)
return getCountOfNode(root->right, l, h);
else return getCountOfNode(root->left, l, h);
}
// } Driver Code Ends
/*The Node structure is
struct Node {
int data;
Node * right, * left;
};*/
/*You are required to complete below method */
class Solution{
public:
void solve(unordered_set<int>&leaf,Node* root){
if(root==NULL) return ;
solve(leaf,root->left);
if(root->left==NULL && root->right==NULL) {
leaf.insert(root->data);
return;
}
solve(leaf,root->right);
}
void solve2(unordered_set<int>&st, Node* root){
if(root==NULL) return;
solve2(st,root->left);
st.insert(root->data);
solve2(st,root->right);
}
bool isDeadEnd(Node *root)
{
//Your code here
Node* temp=root;
unordered_set<int>leaf,st;
solve(leaf,temp);
temp=root;
solve2(st,temp);
st.insert(0);
// for(auto i : leaf){
// cout<<i<<" ";
// }cout<<endl;
// for(auto i : st){
// cout<<i<<" ";
// }
// cout<<endl;
for(auto i : leaf){
auto x =i;
// cout<<i<<" ";
// if(st.find(x-1)!=st.end()){
// cout<<" find"<<endl;
// }
// if(st.find(x+1)!=st.end()){
// cout<<" fined"<<endl;
// }
if(st.find(x-1)!=st.end() && st.find(x+1)!=st.end()) return true;
}
// cout<<endl;
return false ;
}
};
//{ Driver Code Starts.
// bool isDeadEnd(Node *root);
int main()
{
int T;
cin>>T;
while(T--)
{
Node *root;
Node *tmp;
//int i;
root = NULL;
int N;
cin>>N;
for(int i=0;i<N;i++)
{
int k;
cin>>k;
insert(&root, k);
}
Solution ob;
cout<<ob.isDeadEnd(root);
cout<<endl;
}
}
// } Driver Code Ends