LeetCode刷题实战366:寻找二叉树的叶子节点
程序IT圈
共 2083字,需浏览 5分钟
·
2021-09-02 17:02
Given a binary tree, collect a tree’s nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.
依次从左到右,每次收集并删除所有的叶子节点
重复如上过程直到整棵树为空
示例
解题
class Solution:
def findLeaves(self, root: TreeNode) -> List[List[int]]:
res = []
def helper(root):
if not root:
return 0
left = helper(root.left)
right = helper(root.right)
height = max(left, right)
if len(res) == height:
res.append([])
res[height].append(root.val)
return height + 1
helper(root)
return res
评论