Python short and clear solution with one DFS and building solution on the go


  • 2
    H

    Just do a DFS and take the maximum of the depth from left child and right child.
    Leaf nodes have depth 1.

    def findLeaves(self, root):
        ret = []
        def dfs(node):
            if not node:
                return 0
            depth = max(dfs(node.left),dfs(node.right))+1
            if len(ret)<depth:
                ret.append([])
            ret[depth-1].append(node.val)
            return depth
        dfs(root)
        return ret
    

Log in to reply
 

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