-
Notifications
You must be signed in to change notification settings - Fork 0
/
classtree.cpp.cpp
134 lines (106 loc) · 2.17 KB
/
classtree.cpp.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
#include<iostream>
using namespace std;
#include "classtreeheader.h"
class tree
{ private:
node *root;
public:
tree()//default constructor
{
root=0;
}
void treecreate();
void preorder(node *);
void preorder() //note: best use of function overloading
{
preorder(root);
}
void inorder(node *);
void inorder()
{
inorder(root); //note: best use of function overloading
}
void postorder(node *);
void postorder()
{
postorder(root); //note: best use of function overloading
}
};
void tree::treecreate()
{
node *p,*t;
int x;
queue q(100);
cout<<"Enter root value : ";
cin>>x;
root=new node;
root->data=x;
root->lchild = root->rchild=0;
q.enqueue(root);
while(! q.isempty())
{
p= q.dequeue();
cout<<"Enter left child value of "<<p->data<<" : ";
cin>>x;
if(x != -1)
{
t=new node;
t->data=x;
t->lchild=t->rchild=0;
p->lchild=t;
q.enqueue(t);
}
cout<<"Enter right child value of "<<p->data<<" : ";
cin>>x;
if(x != -1)
{
t=new node;
t->data=x;
t->lchild=t->rchild=0;
p->rchild=t;
q.enqueue(t);
}
}
}
void tree::preorder(node *p)
{
//nlr
if(p) //remember to put the terminating if condition
{
cout<<p->data<<" ";
preorder(p->lchild);
preorder(p->rchild);
}
}
void tree::inorder(node *p)
{
//lnr
if(p) //remember to put the terminating if condition
{
inorder(p->lchild);
cout<<p->data<<" ";
inorder(p->rchild);
}
}
void tree::postorder(node *p)
{
//lrn
if(p) //remember to put the terminating if condition
{
postorder(p->lchild);
postorder(p->rchild);
cout<<p->data<<" ";
}
}
main()
{
tree t;
t.treecreate();
cout<<"\n# The PREORDER is : ";
// t.preorder(root); //note:ERROR cant access private variable root from non member function
t.preorder();
cout<<"\n# The INORDER is : ";
t.inorder();
cout<<"\n# The POSTORDER is : ";
t.postorder();
}