Python solution post order, doesn't remove the leaves.

  • 0

    Use post order and a list to track the supposed-to-be removed:

    class Solution(object):
        def findLeaves(self, root):
            :type root: TreeNode
            :rtype: List[List[int]]
            ans, removed = [], []
            while True:
                curLeaves = []
                self.postOrder(root, curLeaves, removed)
                if not curLeaves:
                ans.append([x.val for x in curLeaves])
            return ans
        def postOrder(self, root, leaves, removed):
            if not root or root in removed:
                return None
            self.postOrder(root.left, leaves, removed)
            self.postOrder(root.right, leaves, removed)
            if (not root.left or root.left in removed) and (not root.right or root.right in removed):
            return None

Log in to reply

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