Find Leaves of Binary Tree

Problem: Find Leaves of Binary Tree

We can use depth-first tree to reach leaves and mark their level as 0 and append them to proper position in the result. After that we can return the level back to their parents. Their parents where choose the bigger level from its 2 children and make their own level as that level+1.

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 findLeaves(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        def removeLeaves(node, res):
            if node == None:
                return -1
            index = max(removeLeaves(node.left, res), removeLeaves(node.right, res)) + 1
            while index >= len(res):
                res.append([])
            res[index].append(node.val)
            return index

        res = []
        removeLeaves(root, res)
        return res

results matching ""

    No results matching ""