Skip to content

Commit b15f799

Browse files
committed
vertical order traversal
1 parent 05c4df4 commit b15f799

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

trees/verticalOrderTraversal.py

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
'''
2+
Given a binary tree, return the vertical order traversal of its nodes' values.
3+
(ie, from top to bottom, column by column).
4+
If two nodes are in the same row and column, the order should be from left to right.
5+
'''
6+
7+
def verticalOrder(root):
8+
if not root:return []
9+
queue = [(root,0)]
10+
hashmap = defaultdict(list)
11+
while queue:
12+
node, idx = queue.pop(0)
13+
hashmap[idx] += [node.val]
14+
if node.left:
15+
queue.append((node.left, idx-1))
16+
if node.right:
17+
queue.append((node.right, idx+1))
18+
output = [hashmap[i] for i in sorted(hashmap)]
19+
return output

0 commit comments

Comments
 (0)