-
Notifications
You must be signed in to change notification settings - Fork 2
/
binarytree3.cpp
84 lines (78 loc) · 1.81 KB
/
binarytree3.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
#include <bits/stdc++.h>
using namespace std;
template <typename T>
class BinaryTreeeNode
{
public:
T data;
BinaryTreeeNode* left;
BinaryTreeeNode* right;
BinaryTreeeNode(T a)
{
data=a;
left=NULL;
right=NULL;
}
};
BinaryTreeeNode<int>* TakeInput()
{
int rootdata;
cout<<"enter root data"<<endl;
cin>>rootdata;
if(rootdata==-1)
{
return NULL;
}
BinaryTreeeNode<int>*root=new BinaryTreeeNode<int>(rootdata);
queue<BinaryTreeeNode<int>*> pendingnodes;
pendingnodes.push(root);
while(pendingnodes.size()!=0)
{
BinaryTreeeNode<int>* front=pendingnodes.front();
pendingnodes.pop();
cout<<"enter left chid of "<<front->data<<endl;
int leftchilddata;
cin>>leftchilddata;
if(leftchilddata!=-1)
{
BinaryTreeeNode<int>* leftchild=new BinaryTreeeNode<int>(leftchilddata);
front->left=leftchild;
pendingnodes.push(leftchild);
}
cout<<"enter right chid of "<<front->data<<endl;
int rightchilddata;
cin>>rightchilddata;
if(rightchilddata!=-1)
{
BinaryTreeeNode<int>* rightchild=new BinaryTreeeNode<int>(rightchilddata);
front->right=rightchild;
pendingnodes.push(rightchild);
}
}
return root;
}
void PrintTree(BinaryTreeeNode<int> *root)
{
if (root == NULL)
{
return;
}
cout << root->data << " : ";
if (root->left != NULL)
{
cout << "L." << root->left->data << " ";
}
if (root->right != NULL)
{
cout << "R." << root->right->data << " ";
}
cout << endl;
PrintTree(root->left);
PrintTree(root->right);
}
int main()
{
BinaryTreeeNode<int>* root=TakeInput();
PrintTree(root);
return 0;
}