Description
Given the root of a binary tree, return the vertical order traversal of its nodes’ values. (i.e., from top to bottom, column by column).
If two nodes are in the same row and column, the order should be from left to right.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[9],[3,15],[20],[7]]
Example 2:
Input: root = [3,9,8,4,0,1,7]
Output: [[4],[9],[3,0,1],[8],[7]]
Example 3:
Input: root = [3,9,8,4,0,1,7,null,null,null,2,5]
Output: [[4],[9,5],[3,0,1],[8,2],[7]]
Constraints:
The number of nodes in the tree is in the range [0, 100].
-100 <= Node.val <= 100
Solution
Use a self-defined degree for each node. If the degree for root is 0
, then it would be -1
for left child, and +1
for right child. Use pre-order to traverse the whole tree, and put degree and nodes into a map. In the end, sorted the map and print.
Time complexity:
o
(
n
)
o(n)
o(n)
Space complexity:
o
(
n
)
o(n)
o(n)
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def verticalOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
degree_nodes = {}
queue = collections.deque([(root, 0)])
while queue:
node, degree = queue.popleft()
if degree not in degree_nodes:
degree_nodes[degree] = []
degree_nodes[degree].append(node.val)
if node.left:
queue.append((node.left, degree - 1))
if node.right:
queue.append((node.right, degree + 1))
sorted_degree = sorted(degree_nodes)
res = []
for each_degree in sorted_degree:
res.append(degree_nodes[each_degree])
return res