-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathBoundary Traversal Of Binary Tree
97 lines (88 loc) · 2.64 KB
/
Boundary Traversal Of Binary Tree
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
import java.util.*;
class node{
int data;
node left;
node right;
node(int data){
this.data=data;
left=null;
right=null;
}
}
class tree{
node root;
void printBoundary()
{
if(root==null){
return;
}
node n=root;
if(n.left==null){
System.out.print(n.data+" " );
}
while(n.left!=null){
System.out.print(n.data+" ");
n=n.left;
if(n.left==null){
if(n.right!=null){
while(n.left==null&&n.right!=null){
System.out.print(n.data+" ");
n=n.right;
}
}
}
}
traverser(root);
if(root.right!=null){
n=root.right;
Stack<node>s=new Stack<>();
if(n.right==null&&n.left!=null){
while(n.right==null&&n.left!=null){
s.push(n);
n=n.left;
}
}
while(n.right!=null){
s.push(n);
n=n.right;
if(n.right==null){
if(n.left!=null){
while(n.right==null&&n.left!=null){
s.push(n);
n=n.left;
}
}
}
}
while(!s.isEmpty()){
System.out.print(s.pop().data+" ");
}}
}
void traverser(node n){
if(n.left==null&&n.right==null){
System.out.print(n.data+" ");
}
else{
if(n.left!=null){
traverser(n.left);
}
if(n.right!=null){
traverser(n.right);
}
}
}
}
public class Implementation {
public static void main(String []args){
tree tree=new tree();
tree.root=new node(1);
tree.root.left = new node(2);
tree.root.right = new node(3);
tree.root.left.left = new node(4);
tree.root.left.right = new node(5);
tree.root.right.right = new node(7);
tree.root.right.right.right = new node(8);
tree.root.left.right.right = new node(6);
tree.printBoundary();
}
}