Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 10

Boundary Traversal of Binary Tree

Boundary Traversal of Binary Tree


Given a binary tree, print boundary nodes of the binary tree Anti-Clockwise starting from the root.

The boundary includes

1. left boundary (nodes on left excluding leaf nodes)


2. leaves (consist of only the leaf nodes)
3. right boundary (nodes on right excluding leaf nodes)
Boundary Traversal of Binary Tree
1 import java.util.*;
2 import java.util.Map.Entry;
3 class Node {
4 int data;
5 Node left, right;
6 public Node(int data){
7 this.data = data;
8 left = right = null;
9 }
10 }
11
12 class Main {
13 static Node root;
14 private List<Integer> path1 = new ArrayList<>();
15 private List<Integer> path2 = new ArrayList<>();
16 static Node build(String s[]){
17 if(s[0]=="N"||s.length==0)
18 return null;
19 Node root=new Node(Integer.parseInt(s[0]));
20 Queue<Node> q=new LinkedList<Node>();
21 q.add(root);
22
23 int i=1;
24 while(!q.isEmpty() && i<s.length){
25 Node curr=q.poll();
26 String cval=s[i];
27 if(!cval.equals("N")){
28 int h=Integer.parseInt(cval);
29 curr.left=new Node(h);
30 q.add(curr.left);
31 }
32 i++;
33 if(i >= s.length)
34 break;
35 cval = s[i];
36 if(!cval.equals("N")){
37 int h=Integer.parseInt(cval);
38 curr.right=new Node(h);
39 q.add(curr.right);
40 }
41 i++;
42 }
43 return root;
44 }
45 //print the leaves
46 void printLeaves(Node node){
47 if (node == null)
48 return;
49 printLeaves(node.left);
50 if (node.left == null && node.right == null)
51 System.out.print(node.data + " ");
52 printLeaves(node.right);
53 }
54 //left boundary
55 void printBoundaryLeft(Node node){
56 if (node == null)
57 return;
58 if (node.left != null) {
59 System.out.print(node.data + " ");
60 printBoundaryLeft(node.left);
61 }
62 else if (node.right != null) {
63 System.out.print(node.data + " ");
64 printBoundaryLeft(node.right);
65 }
66 }
67 //right boundary
68 void printBoundaryRight(Node node){
69 if (node == null)
70 return;
71 if (node.right != null) {
72 printBoundaryRight(node.right);
73 System.out.print(node.data + " ");
74 }
75 else if (node.left != null) {
76 printBoundaryRight(node.left);
77 System.out.print(node.data + " ");
78 }
79 }
80 void printBoundary(Node node){
81 if (node == null)
82 return;
83 System.out.print(node.data + " ");
84 printBoundaryLeft(node.left);
85 printLeaves(node.left);
86 printLeaves(node.right);
87 printBoundaryRight(node.right);
88 }
89 //main method
90 public static void main(String[] args){
91 Scanner sc=new Scanner(System.in);
92 int i;
93 Main ob = new Main();
94 String s[]=sc.nextLine().split(" ");
95 root = build(s);
96 ob.printBoundary(root);
97 }
98 }
99
100
101
102
103
104
105
106
107
108
109
110
THANK YOU

You might also like