-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBinaryTrees.cpp
More file actions
105 lines (90 loc) · 1.85 KB
/
BinaryTrees.cpp
File metadata and controls
105 lines (90 loc) · 1.85 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
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
struct node
{
int data;
node *right;
node *left;
};
node *getNewNode(int data)
{
node *newnode =new node();
newnode->data=data;
newnode->left=NULL;
newnode->right=NULL;
return newnode;
}
node *insertNode(node* root,int data)
{
if(root==NULL)
{
root=getNewNode(data);
}
else if(data<=root->data)
{
root->left=insertNode(root->left,data);
}
else
{
root->right=insertNode(root->right,data);
}
return root;
}
bool SearchNode(node *root,int data)
{
if(root==NULL)
return false;
if(root->data==data)
return true;
if(data<=root->data) return SearchNode(root->left,data);
else return SearchNode(root->right,data);
}
void preorderTraversal(node *root)
{
if (root==nullptr)
return;
cout<<root->data<<" ";
preorderTraversal(root->left);
preorderTraversal(root->right);
}
void Levelorder(node *root)
{
if(root==NULL)
return;
queue<node*> Q;
Q.push(root);
while(!Q.empty())
{
node *current=Q.front();
cout<<current->data<<" ";
if(current->left!=NULL)
Q.push(current->left);
if(current->right!=NULL)
Q.push(current->right);
Q.pop();
}
}
int main()
{
node *root=NULL;
root=insertNode(root,10);
root=insertNode(root,1);
root=insertNode(root,20);
root=insertNode(root,4);
root=insertNode(root,3);
root=insertNode(root,21);
root=insertNode(root,9);
root=insertNode(root,23);
root=insertNode(root,14);
int num;
cout<<"enter a number :";
cin>>num;
if(SearchNode(root,num)==true)
cout<<"match found"<<endl;
else
cout<<"match not found"<<endl;
Levelorder(root);
cout<<endl;
preorderTraversal(root);
}