Short and Concise DFS based Python Solution


  • 0
    U
    # 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 findLeaves(self, root):
            self.depth = []
            self.leaves(root)
            return self.depth
            
        def leaves(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[int]]
            """
            if not root:
                return -1
                
            left_height = self.leaves(root.left)
            right_height = self.leaves(root.right)
            
            height = max(left_height, right_height) + 1
            
            if height < len(self.depth):
                self.depth[height].append(root.val)
            else:
                self.depth.append([root.val])
            
            return height
            
    

Log in to reply
 

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