Python DFS Solution


  • 0
    D
    # 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 largestValues(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            arr = []
            def search(node, depth):
                if not node: return
                if len(arr) < depth + 1:
                    arr.append(node.val)
                else:
                    arr[depth] = max(arr[depth], node.val)
                search(node.left, depth + 1)
                search(node.right, depth + 1)
            search(root, 0)
            return arr

Log in to reply
 

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