Skip to content

Commit b386c27

Browse files
add a solution for 314
1 parent 3baf525 commit b386c27

File tree

1 file changed

+41
-0
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+41
-0
lines changed

Diff for: src/main/java/com/fishercoder/solutions/_314.java

+41
Original file line numberDiff line numberDiff line change
@@ -96,4 +96,45 @@ public List<List<Integer>> verticalOrder(TreeNode root) {
9696
}
9797
}
9898

99+
public static class Solution3 {
100+
public List<List<Integer>> verticalOrder(TreeNode root) {
101+
if (root == null) {
102+
return new ArrayList<>();
103+
}
104+
TreeMap<Integer, List<Integer>> map = new TreeMap<>();
105+
Queue<NodeWithIndex> queue = new LinkedList<>();
106+
queue.offer(new NodeWithIndex(root, 0));
107+
while (!queue.isEmpty()) {
108+
int size = queue.size();
109+
for (int i = 0; i < size; i++) {
110+
NodeWithIndex nodeWithIndex = queue.poll();
111+
List<Integer> thisList = map.getOrDefault(nodeWithIndex.index, new ArrayList<>());
112+
thisList.add(nodeWithIndex.node.val);
113+
map.put(nodeWithIndex.index, thisList);
114+
if (nodeWithIndex.node.left != null) {
115+
queue.offer(new NodeWithIndex(nodeWithIndex.node.left, nodeWithIndex.index - 1));
116+
}
117+
if (nodeWithIndex.node.right != null) {
118+
queue.offer(new NodeWithIndex(nodeWithIndex.node.right, nodeWithIndex.index + 1));
119+
}
120+
}
121+
}
122+
List<List<Integer>> result = new ArrayList<>();
123+
for (int index : map.keySet()) {
124+
result.add(map.get(index));
125+
}
126+
return result;
127+
}
128+
129+
class NodeWithIndex {
130+
TreeNode node;
131+
int index;
132+
133+
public NodeWithIndex(TreeNode node, int index) {
134+
this.node = node;
135+
this.index = index;
136+
}
137+
}
138+
}
139+
99140
}

0 commit comments

Comments
 (0)