-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTree.cpp
83 lines (73 loc) · 1.53 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
#include<iostream>
using namespace std;
struct tree{
tree*left=NULL;
int data;
tree*right=NULL;
};
//This check function check the right position and insert the node;
void check(tree*leafNode,tree*node){
if(node->data>leafNode->data){
if(leafNode->right==NULL){
leafNode->right=node;
}else{
check(leafNode->right,node);
}
}else if(node->data<leafNode->data){
if(leafNode->left==NULL){
leafNode->left=node;
}else{
check(leafNode->left,node);
}
}else{
cout<<"\n\nDATA SHOULD BE INDENTICAL";
}
}
tree*createTree(int n){
tree*root=NULL;
//Create a node and initilize it.
for(int i=1;i<=n;i++){
tree*node=new tree();
cout<<"\nEnter data "<<i<<": ";
cin>>node->data;
node->left=NULL;
node->right=NULL;
if(root==NULL){
root=node;
}else{
check(root,node);
}
}
return root;
}
void inorder(tree*root){
if(root!=NULL){
inorder(root->left);
cout<<" | "<<root->data;
inorder(root->right);
}
}
void preorder(tree*root){
if(root!=NULL){
cout<<" | "<<root->data;
preorder(root->left);
preorder(root->right);
}
}
void postorder(tree*root){
if(root!=NULL){
postorder(root->left);
postorder(root->right);
cout<<" | "<<root->data;
}
}
int main(){
tree*ROOT=createTree(5);
cout<<"\nInorder: ";
inorder(ROOT);
cout<<"\nPreorder: ";
preorder(ROOT);
cout<<"\nPostorder: ";
postorder(ROOT);
return 0;
}