This repository was archived by the owner on Sep 23, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBST.cpp
More file actions
128 lines (124 loc) · 2.14 KB
/
Copy pathBST.cpp
File metadata and controls
128 lines (124 loc) · 2.14 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
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
#include <iostream>
using namespace std;
struct node{
int key;
node* left;
node* right;
node* parent;
};
class Tree{
private:
struct node* root;
int num;
public:
Tree(){
root=new struct node;
root -> left=NULL;
root -> right=NULL;
num=0;
}
void insert(int k){
struct node* temp2=new struct node;
temp2 -> key=k;
temp2 -> left=NULL;
temp2 -> right=NULL;
temp2 -> parent=NULL;
if(num==0){
root=temp2;
num++;
return;
}
struct node* temp1=root;
while(true){
if(temp1 -> key<k){
if(temp1 -> left){
temp1=temp1 -> left;
}
else{
temp1 -> left=temp2;
temp2 -> parent=temp1;
num++;
return;
}
}
else{
if(temp1 -> right){
temp1=temp1 -> right;
}
else{
temp1 -> right=temp2;
temp2 -> parent=temp1;
num++;
return;
}
}
}
}
void preorder(struct node* start){
cout<<start -> key<<endl;
if(start -> left){
cout<<"Left :";
preorder(start -> left);
}
if(start -> right){
cout<<"Right :";
preorder(start -> right);
}
}
void display(){
preorder(root);
}
int size(){
return num;
}
struct node* find(struct node* start,int k){
if(start -> key==k)
return start;
struct node* tempL;
if(start -> left)
tempL=find(start -> left,k);
else
tempL=NULL;
struct node* tempR;
if(start -> right)
tempR=find(start -> right,k);
else
tempR=NULL;
return tempR==NULL?tempL:tempR;
}
struct node* find(int k){
return find(root,k);
}
/*void remove(int k){
struct node* temp1=find(k);
if(temp1==root){
root
struct node* temp2=temp1 -> parent;
if(temp1 -> key<temp2 -> key){
temp2 -> left=temp1 -> left;
(temp1 -> left) -> parent=temp2;
(temp1 -> right) -> parent=temp1 -> left;
num--;
}
else{
temp2 -> right=temp1 -> right;
(temp1 -> right) -> parent=temp2;
(temp1 -> left) -> parent=temp1 -> right;
num--;
}
}*/
};
int n;
int main(){
cin>>n;
Tree A;
for(int i=0;i<n;i++){
int x;
cin>>x;
A.insert(x);
}
A.display();
int y;
cin>>y;
cout<<A.find(y) -> key<<endl;
}