-
Notifications
You must be signed in to change notification settings - Fork 0
/
boundary_elements_of_tree.cpp
128 lines (100 loc) · 1.94 KB
/
boundary_elements_of_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
120
121
122
123
124
125
126
127
128
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
};
void printLeaves(Node* root)
{
if (root == NULL)
return;
printLeaves(root->left);
if (!(root->left) && !(root->right))
printf("%d ", root->data);
printLeaves(root->right);
}
void printBoundaryLeft(Node* root)
{
if (root == NULL)
return;
if (root->left) {
printf("%d ", root->data);
printBoundaryLeft(root->left);
}
else if (root->right) {
printf("%d ", root->data);
printBoundaryLeft(root->right);
}
}
void printBoundaryRight(Node* root)
{
if (root == NULL)
return;
if (root->right) {
printBoundaryRight(root->right);
printf("%d ", root->data);
}
else if (root->left) {
printBoundaryRight(root->left);
printf("%d ", root->data);
}
}
void printBoundary(Node* root)
{
if (root == NULL)
return;
printf("%d ", root->data);
printBoundaryLeft(root->left);
printLeaves(root->left);
printLeaves(root->right);
printBoundaryRight(root->right);
}
Node* newNode(int data)
{
Node* temp = new Node();
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
Node* insertNode(Node* root, int data)
{
if (root == NULL) {
root = newNode(data);
return root;
}
queue<Node*> q;
q.push(root);
while (!q.empty()) {
Node* temp = q.front();
q.pop();
if (temp->left != NULL)
q.push(temp->left);
else {
temp->left = newNode(data);
return root;
}
if (temp->right != NULL)
q.push(temp->right);
else {
temp->right = newNode(data);
return root;
}
}
}
int main()
{
int n,num;
Node* root = NULL;
cout<<"Enter the number of nodes in tree : ";
cin>>n;
cout<<"Enter the nodes in level order : ";
for(int i=0;i<n;i++)
{
cin>>num;
root=insertNode(root,num);
}
cout<<"The boundary elements are : ";
printBoundary(root);
return 0;
}