-
Notifications
You must be signed in to change notification settings - Fork 0
/
boundary_traversal.java
58 lines (57 loc) · 1.61 KB
/
boundary_traversal.java
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
import java.util.ArrayList;
public class traversal {
class Node
{
int data;
Node left, right;
public Node(int d)
{
data = d;
left = right = null;
}
}
ArrayList<Integer> boundary(Node node){
ArrayList<Integer>res = new ArrayList<Integer>(0);
if(node != null){
res.add(node.data);
}
printboundaryleft(node.left,res);
printleaves(node.left,res);
printleaves(node.right,res);
printboundaryright(node.right,res);
return res;
}
private void printleaves(Node node, ArrayList<Integer> res) {
if(node!=null){
printleaves(node.left, res);
if(node.left == null && node.right == null){
res.add(node.data);
}
printleaves(node.right, res);
}
}
private void printboundaryright(Node node, ArrayList<Integer> res) {
if(node!=null){
if(node.right!=null){
printboundaryright(node.right, res);
res.add(node.data);
}
else if(node.left!=null){
printboundaryright(node.left, res);
res.add(node.data);
}
}
}
private void printboundaryleft(Node node, ArrayList<Integer> res) {
if(node!= null){
if(node.left!= null){
res.add(node.data);
printboundaryleft(node.left, res);
}
else if(node.right!=null){
res.add(node.data);
printboundaryleft(node.right, res);
}
}
}
}