Skip to content

366 Find Leaves of Binary Tree

366. Find Leaves of Binary Tree

题目:

https://leetcode.com/problems/find-leaves-of-binary-tree/

难度 :Medium

按照它的要求,老老实实写了两个递归 findleaf 和 deleteleaf, 再组合起来

AC代码

class Solution(object):
    def findLeaves(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        def findLeaf(root):
            if not root:
                return []
            elif not root.left and not root.right:
                return [root.val]
            else:
                return findLeaf(root.left) + findLeaf(root.right)
        def removeLeaf(root):
            if not root:
                return None
            elif not root.left and not root.right:
                return None
            else:
                if root.left:
                    root.left = removeLeaf(root.left)
                if root.right:
                    root.right = removeLeaf(root.right)
                return root
        res = []
        while root:
            res.append(findLeaf(root))
            root = removeLeaf(root)
        return res

我们一直在努力

apachecn/AiLearning

【布客】中文翻译组