|
22 | 22 | */
|
23 | 23 | public class VerticalOrderTraversal {
|
24 | 24 |
|
25 |
| - public static void main(String[] args) { |
26 |
| - BinaryTree tree = new BinaryTree(); |
27 |
| - tree.put(5); |
28 |
| - tree.put(6); |
29 |
| - tree.put(3); |
30 |
| - tree.put(1); |
31 |
| - tree.put(4); |
32 |
| - BinaryTree.Node root = tree.getRoot(); |
33 |
| - ArrayList<Integer> ans = verticalTraversal(root); |
34 |
| - for (int i : ans) { |
35 |
| - System.out.print(i + " "); |
| 25 | + /*Function that receives a root Node and prints the tree |
| 26 | + in Vertical Order.*/ |
| 27 | + public static ArrayList<Integer> verticalTraversal(BinaryTree.Node root) { |
| 28 | + if (root == null) { |
| 29 | + return new ArrayList<>(); |
36 | 30 | }
|
37 |
| - } |
38 | 31 |
|
39 |
| - /*Function that receives a root Node and prints the tree |
40 |
| - in Vertical Order.*/ |
41 |
| - private static ArrayList<Integer> verticalTraversal(BinaryTree.Node root) { |
42 | 32 | /*Queue to store the Nodes.*/
|
43 | 33 | Queue<BinaryTree.Node> queue = new LinkedList<>();
|
44 | 34 |
|
@@ -84,21 +74,19 @@ private static ArrayList<Integer> verticalTraversal(BinaryTree.Node root) {
|
84 | 74 | to the respective ArrayList present at that
|
85 | 75 | index. */
|
86 | 76 | map.get(index.peek()).add(queue.peek().data);
|
87 |
| - max = (int) Math.max(max, index.peek()); |
88 |
| - min = (int) Math.min(min, index.peek()); |
89 |
| - /*The Node and its index are removed |
| 77 | + max = Math.max(max, index.peek()); |
| 78 | + min = Math.min(min, index.peek()); |
| 79 | + /*The Node and its index are removed |
90 | 80 | from their respective queues.*/
|
91 | 81 | index.poll();
|
92 | 82 | queue.poll();
|
93 | 83 | }
|
94 | 84 | /*Finally map data is printed here which has keys
|
95 |
| - from min to max. Each ArrayList represents a |
| 85 | + from min to max. Each ArrayList represents a |
96 | 86 | vertical column that is added in ans ArrayList.*/
|
97 | 87 | ArrayList<Integer> ans = new ArrayList<>();
|
98 | 88 | for (int i = min; i <= max; i++) {
|
99 |
| - for (int j = 0; j < map.get(i).size(); j++) { |
100 |
| - ans.add(map.get(i).get(j)); |
101 |
| - } |
| 89 | + ans.addAll(map.get(i)); |
102 | 90 | }
|
103 | 91 | return ans;
|
104 | 92 | }
|
|
0 commit comments