We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 05c4df4 commit b15f799Copy full SHA for b15f799
trees/verticalOrderTraversal.py
@@ -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