-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy path0987-vertical-order-traversal-of-a-binary-tree.py
48 lines (37 loc) · 1.18 KB
/
0987-vertical-order-traversal-of-a-binary-tree.py
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
# time complexity: O(n)
# space complexity: O(n)
from typing import List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def verticalTraversal(self, root: TreeNode) -> List[List[int]]:
nodeList = []
def DFS(node, row, column):
if node is not None:
nodeList.append((column, row, node.val))
# preorder DFS
DFS(node.left, row + 1, column - 1)
DFS(node.right, row + 1, column + 1)
DFS(root, 0, 0)
nodeList.sort()
ret = []
currColumnIndex = nodeList[0][0]
currColumn = []
for column, row, value in nodeList:
if column == currColumnIndex:
currColumn.append(value)
else:
ret.append(currColumn)
currColumnIndex = column
currColumn = [value]
ret.append(currColumn)
return ret
root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right.left = TreeNode(15)
root.right.right = TreeNode(7)
print(Solution().verticalTraversal(root))