-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBoundaryPoint.cpp
More file actions
85 lines (78 loc) · 1.7 KB
/
BoundaryPoint.cpp
File metadata and controls
85 lines (78 loc) · 1.7 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
#include<iostream>
#include<climits>
#include<queue>
using namespace std;
struct Node{
int data;
Node* left;
Node* right;
};
Node* newNode(int data){
Node* node = new Node();
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
void printLeftBoundary(Node* root){
if(root == NULL)
return;
cout<<root->data<<" ";
if(root->left == NULL) printLeftBoundary(root->right);
else printLeftBoundary(root->left);
}
void printRightBoundary(Node* root){
if(root == NULL)
return;
if(root->right != NULL){
printRightBoundary(root->right);
cout<<root->data<<" ";
}
else if(root->left != NULL){
printRightBoundary(root->left);
cout<<root->data<<" ";
}
}
void printLeaves(Node* root){
if(root == NULL)
return;
printLeaves(root->left);
if(root->left == NULL && root->right == NULL)
cout<<root->data<<" ";
printLeaves(root->right);
}
Node* BuildTree(int inorder[],int n){
queue<Node*> q;
Node* root = newNode(inorder[0]);
q.push(root);
int i = 1;
int j = 2;
while(i < n && !q.empty()){
Node* current = q.front();
q.pop();
Node* left ;
Node* right = newNode(inorder[j]);
if(inorder[i] != INT_MIN) left = newNode(inorder[i]);
else left = NULL;
current->left = left;
if (inorder[j] != INT_MIN && j!=n) right = newNode(inorder[j]);
else right = NULL;
current->right = right;
if(left != NULL) q.push(left);
if(right != NULL) q.push(right);
i+=2;
j+=2;
}
return root;
}
int main(){
int inorder[] = {1,2,3,4,5,6,7,8,9,10,11,12,13};
int n = sizeof(inorder)/sizeof(inorder[0]);
Node* root = BuildTree(inorder,n);
cout<<"Boundary Traversal of the tree is: ";
printLeftBoundary(root);
printLeaves(root);
printRightBoundary(root->right);
cout<<endl;
return 0;
}