Python Elegant DFS 90% Quantile

  • 0
    # 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]]
            self.res = {}
            self.dfs(root, 0, 0)
            self.res = [sorted(self.res[k], key=lambda x: x[1]) for k in sorted(self.res)]
            return [[x[0] for x in e] for e in self.res]
        def dfs(self, node, level, depth):
            if node:
                self.res[level] = self.res.get(level, []) + [(node.val,depth)]
                self.dfs(node.left, level-1, depth+1)
                self.dfs(node.right, level+1, depth+1)

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.