-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTree.cpp
119 lines (107 loc) · 1.66 KB
/
Tree.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
#include<iostream>
#include<queue>
using namespace std;
class Node
{
public:
int data;
Node* left;
Node* right;
};
class Tree
{
private:
Node* root;
public:
Tree()
{
this->root=NULL;
}
void CreateTree();
void Traverse(){Traverse(root);}
void Traverse(Node* p);
void BST(int k){BST(root,k);}
void BST(Node* p,int k);
};
void Tree::CreateTree()
{
queue<Node*> q;
int x;
this->root=new Node();
this->root->left=root->right=NULL;
cout<<"Enter root Node value";
cin>>x;
root->data=x;
q.push(root);
while(!q.empty())
{
Node* p=q.front();
q.pop();
int k;
cout<<"enter left child value if present else -1:"<<endl;
cin>>k;
if(k!=-1)
{
Node* temp=new Node();
temp->left=NULL;
temp->right=NULL;
temp->data=k;
q.push(temp);
p->left=temp;
temp=NULL;
}
else
{
p->left=NULL;
}
cout<<"enter right child value if present else -1:"<<endl;
cin>>k;
if(k!=-1)
{
Node* temp=new Node();
temp->left=NULL;
temp->right=NULL;
temp->data=k;
q.push(temp);
p->right=temp;
temp=NULL;
}else
{
p->right=NULL;
}
}
}
void Tree:: Traverse(Node* temp)
{
if(temp)
{
cout<<temp->data<<" ";
Traverse(temp->left);
Traverse(temp->right);
}
}
void Tree::BST(Node* temp,int k)
{
if(temp->data==k)
{
cout<<"key found";
return;
}
else if(temp->data>k)
{
BST(temp->left,k);
}
else if(temp->data<k)
{
BST(temp->right,k);
}
else return;
}
int main()
{
Tree t;
t.CreateTree();
t.Traverse();
t.BST(10);
return 0;
}