|
1 | 1 | package binaryTree; |
2 | | - |
| 2 | +/* |
| 3 | + * Problem Title :- Boundary traversal of a Binary tree |
| 4 | + */ |
3 | 5 | public class BT_Problem_16 { |
4 | 6 |
|
| 7 | + Node root; |
| 8 | + // printing leaf nodes |
| 9 | + void printLeaves(Node node) { |
| 10 | + if(node == null) |
| 11 | + return; |
| 12 | + |
| 13 | + printLeaves(node.left); |
| 14 | + // print if it is a leaf node |
| 15 | + if(node.left == null && node.right == null) |
| 16 | + System.out.print(node.data + " "); |
| 17 | + printLeaves(node.right); |
| 18 | + } |
| 19 | + |
| 20 | + void printBoundaryLeft(Node node) { |
| 21 | + if(node == null) |
| 22 | + return; |
| 23 | + if(node.left != null) { |
| 24 | + System.out.print(node.data + " "); |
| 25 | + printBoundaryLeft(node.left); |
| 26 | + } |
| 27 | + |
| 28 | + else if(node.right != null) { |
| 29 | + System.out.print(node.data + " "); |
| 30 | + printBoundaryLeft(node.right); |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + void printBoundaryRight(Node node) { |
| 35 | + if(node == null) |
| 36 | + return; |
| 37 | + if(node.left != null) { |
| 38 | + System.out.print(node.data + " "); |
| 39 | + printBoundaryRight(node.left); |
| 40 | + } |
| 41 | + |
| 42 | + else if(node.right != null) { |
| 43 | + System.out.print(node.data + " "); |
| 44 | + printBoundaryRight(node.right); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + void printBoundary(Node node) { |
| 49 | + if(node == null) |
| 50 | + return; |
| 51 | + |
| 52 | + System.out.print(node.data + " "); |
| 53 | + |
| 54 | + printBoundaryLeft(node.left); |
| 55 | + |
| 56 | + printLeaves(node.left); |
| 57 | + printLeaves(node.right); |
| 58 | + |
| 59 | + printBoundaryRight(node.right); |
| 60 | + } |
| 61 | + |
5 | 62 | public static void main(String[] args) { |
6 | | - // TODO Auto-generated method stub |
| 63 | + BT_Problem_16 tree = new BT_Problem_16(); |
| 64 | + |
| 65 | + tree.root = new Node(1); |
| 66 | + tree.root.left = new Node(2); |
| 67 | + tree.root.left.left = new Node(4); |
| 68 | + tree.root.left.right = new Node(5); |
| 69 | + tree.root.left.left.left = new Node(8); |
| 70 | + tree.root.left.right.left = new Node(10); |
| 71 | + tree.root.left.right.right = new Node(14); |
| 72 | + tree.root.right = new Node(3); |
| 73 | + tree.root.right.right = new Node(22); |
| 74 | + |
| 75 | + tree.printBoundary(tree.root); |
7 | 76 |
|
8 | 77 | } |
9 | 78 |
|
|
0 commit comments