-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVerticalOrderTraversalHashmap.java
94 lines (73 loc) · 2.26 KB
/
VerticalOrderTraversalHashmap.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
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
package com.company;
import javafx.util.Pair;
import java.io.*;
import java.lang.*;
import java.util.*;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
left=null;
right=null;
}
}
class Values{
int min,max;
}
public class Main {
TreeNode root;
public static ArrayList<Integer> result = new ArrayList<Integer>();
public static void main(String[] args) {
// write your code here
System.out.println("Executing byte code");
Values val = new Values();
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
TreeMap<Integer, ArrayList<Integer>> map = new TreeMap<>();
int hd =0;
getVerticalOrder(root,hd,map);
// Traverse the map and print nodes at every horigontal
// distance (hd)
}
static ArrayList<ArrayList<Integer>> getVerticalOrder(TreeNode root, int hd, TreeMap<Integer, ArrayList<Integer>> m) {
// Base case
Queue<Pair<TreeNode,Integer>> que = new LinkedList<>();
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
if(root == null)
return result;
que.add(new Pair(root,hd));
while (que.isEmpty()== false)
{
// pop from queue front
Pair<TreeNode ,Integer> temp = que.peek();
que.poll();
hd = temp.getValue();
TreeNode node = temp.getKey();
//get the vector list at 'hd'
ArrayList<Integer> get = m.get(hd);
// Store current node in map 'm'
if(get == null)
{
get = new ArrayList<Integer>();
get.add(node.val);
}
else
get.add(node.val);
m.put(hd, get);
if (node.left != null)
que.add(new Pair(node.left, hd-1));
if (node.right != null)
que.add(new Pair(node.right, hd+1));
}
for (Map.Entry<Integer, ArrayList<Integer>> entry : m.entrySet())
{
result.add(entry.getValue());
}
return result;
}
}