|
| 1 | +#================================================== |
| 2 | +#==> Title: |
| 3 | +#==> Author: Zhang zhen |
| 4 | +#==> Email: hustmatnoble.gmail.com |
| 5 | +#==> GitHub: https://github.com/MatNoble |
| 6 | +#==> Date: |
| 7 | +#================================================== |
| 8 | + |
| 9 | +from typing import List |
| 10 | +import collections |
| 11 | +# Definition for a binary tree node. |
| 12 | +class TreeNode: |
| 13 | + def __init__(self, val=0, left=None, right=None): |
| 14 | + self.val = val |
| 15 | + self.left = left |
| 16 | + self.right = right |
| 17 | + |
| 18 | +class Solution: |
| 19 | + def verticalTraversal(self, root: TreeNode) -> List[List[int]]: |
| 20 | + vertical = collections.defaultdict(list) |
| 21 | + |
| 22 | + queue = collections.deque() |
| 23 | + queue.append((root, 0, 0)) |
| 24 | + while queue: |
| 25 | + node, row, col = queue.popleft() |
| 26 | + vertical[col].append([row, node.val]) |
| 27 | + if node.left: |
| 28 | + queue.append((node.left, row+1, col-1)) |
| 29 | + if node.right: |
| 30 | + queue.append((node.right, row+1, col+1)) |
| 31 | + # def dfs(node,row=0,col=0): |
| 32 | + # if node is None: return None |
| 33 | + # dfs(node.left ,row+1,col-1) |
| 34 | + # dfs(node.right ,row+1,col+1) |
| 35 | + # vertical[col].append([row, node.val]) |
| 36 | + # dfs(root) |
| 37 | + return [ [node_value for row_value, node_value in sorted(values)] for col_value, values in sorted(vertical.items())] |
| 38 | + |
| 39 | + |
| 40 | +root = TreeNode(1) |
| 41 | +root.left = TreeNode(2) |
| 42 | +root.right = TreeNode(3) |
| 43 | +root.left.left = TreeNode(4) |
| 44 | +root.left.right = TreeNode(6) |
| 45 | +root.right.left = TreeNode(5) |
| 46 | +root.right.right = TreeNode(7) |
| 47 | + |
| 48 | +mat = Solution() |
| 49 | +mat.verticalTraversal(root) |
0 commit comments