Binary Tree Vertical Order Traversal

Problem: Binary Tree Vertical Order Traversal

We use a hash table to maintain vertical order traversal. The keys should be the number of rows and every time we scan a new node we can add it to appropriate key and its left child to previous key and right child to next key.

Code in Python:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution(object):
    def verticalOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        dict = collections.defaultdict(list)
        queue = [(root, 0)]
        for node, i in queue:
            if node:
                dict[i].append(node.val)
                queue.append((node.left, i-1))
                queue.append((node.right, i+1))
        return [dict[i] for i in sorted(dict)]

results matching ""

    No results matching ""