Skip to content

Commit 3fdfb09

Browse files
987 Vertical Order Traversal of a Binary Tree.py
1 parent 88c543a commit 3fdfb09

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
#!/usr/bin/python3
2+
"""
3+
Given a binary tree, return the vertical order traversal of its nodes values.
4+
5+
For each node at position (X, Y), its left and right children respectively will
6+
be at positions (X-1, Y-1) and (X+1, Y-1).
7+
8+
Running a vertical line from X = -infinity to X = +infinity, whenever the
9+
vertical line touches some nodes, we report the values of the nodes in order
10+
from top to bottom (decreasing Y coordinates).
11+
12+
If two nodes have the same position, then the value of the node that is
13+
reported first is the value that is smaller.
14+
15+
Return an list of non-empty reports in order of X coordinate. Every report
16+
will have a list of values of nodes.
17+
18+
Example 1:
19+
20+
Input: [3,9,20,null,null,15,7]
21+
Output: [[9],[3,15],[20],[7]]
22+
Explanation:
23+
Without loss of generality, we can assume the root node is at position (0, 0):
24+
Then, the node with value 9 occurs at position (-1, -1);
25+
The nodes with values 3 and 15 occur at positions (0, 0) and (0, -2);
26+
The node with value 20 occurs at position (1, -1);
27+
The node with value 7 occurs at position (2, -2).
28+
Example 2:
29+
30+
Input: [1,2,3,4,5,6,7]
31+
Output: [[4],[2],[1,5,6],[3],[7]]
32+
Explanation:
33+
The node with value 5 and the node with value 6 have the same position according to the given scheme.
34+
However, in the report "[1,5,6]", the node value of 5 comes first since 5 is smaller than 6.
35+
36+
37+
Note:
38+
39+
The tree will have between 1 and 1000 nodes.
40+
Each node's value will be between 0 and 1000.
41+
"""
42+
43+
44+
# Definition for a binary tree node.
45+
class TreeNode:
46+
def __init__(self, x):
47+
self.val = x
48+
self.left = None
49+
self.right = None
50+
51+
52+
from collections import defaultdict
53+
54+
55+
class Solution:
56+
def __init__(self):
57+
self.mp = defaultdict(list) # element (-Y, val) # from left to right, top to bottom
58+
59+
def verticalTraversal(self, root: TreeNode) -> List[List[int]]:
60+
self.dfs(root, 0, 0)
61+
ret = []
62+
mn = min(self.mp)
63+
mx = max(self.mp)
64+
for i in range(mn, mx+1):
65+
ret.append([
66+
val
67+
for _, val in sorted(self.mp[i])
68+
])
69+
return ret
70+
71+
def dfs(self, node, x, y):
72+
if not node:
73+
return
74+
self.mp[x].append((-y, node.val))
75+
self.dfs(node.left, x-1, y-1)
76+
self.dfs(node.right, x+1, y-1)

0 commit comments

Comments
 (0)