0
点赞
收藏
分享

微信扫一扫

LeetCode 366. Find Leaves of Binary Tree - 二叉树(Binary Tree)系列题9

Given the root of a binary tree, collect a tree's nodes as if you were doing this:

  • Collect all the leaf nodes.
  • Remove all the leaf nodes.
  • Repeat until the tree is empty.

Example 1:

Input: root = [1,2,3,4,5]
Output: [[4,5,3],[2],[1]]
Explanation:
[[3,5,4],[2],[1]] and [[3,4,5],[2],[1]] are also considered correct answers since per each level it does not matter the order on which elements are returned.

Example 2:

Input: root = [1]
Output: [[1]]

Constraints:

  • The number of nodes in the tree is in the range [1, 100].
  • -100 <= Node.val <= 100

 题目给定一棵二叉树,要求把所有叶节点值放入一个数组中,然后把所有叶节点都删除,这样树中就又有一些节点变成了新的叶节点,重复同样的动作就像剥洋葱一样一层一层地把叶节点去掉,直到最后只剩一个根节点。

因此一个节点在第几层被剥离决定了它在结果中的位置,而一个节点是在第几层被剥离又取决于它的左右子树的最大高度,根据题意要剥离一个节点肯定要等到其所有子节点都被剥离了,因此左右子树最大高度的更大者加1就是那个节点的层数。

class Solution:
    def findLeaves(self, root: Optional[TreeNode]) -> List[List[int]]:
        if not root:
            return []
        
        res = []
        
        def helper(node):
            nonlocal res
            if not node:
                return 0
            if not node.left and not node.right:
                if len(res) == 0:
                    res.append([])
                res[0].append(node.val)
                return 1
            ld = helper(node.left)
            rd = helper(node.right)
            
            d = max(ld, rd)
            if len(res) == d:
                res.append([])
            res[d].append(node.val)
            
            return d + 1
        helper(root)
        
        return res
举报

相关推荐

0 条评论