-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvertical_tree_print.py
More file actions
30 lines (23 loc) · 839 Bytes
/
vertical_tree_print.py
File metadata and controls
30 lines (23 loc) · 839 Bytes
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
# https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
from collections import defaultdict
class Solution:
def verticalTraversal(self, root: TreeNode) -> List[List[int]]:
result = defaultdict(list)
def dfs(root, level, height):
if not root:
return
result[level].append((height, root.val))
dfs(root.left, level - 1, height + 1)
dfs(root.right, level + 1, height + 1)
dfs(root, 0, 0)
answer = []
levels = sorted(result.keys())
for level in levels:
answer.append(list(map(lambda y: y[1], sorted(result[level]))))
return answer