?LeetCode刷題實戰(zhàn)366:尋找二叉樹的葉子節(jié)點
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.
依次從左到右,每次收集并刪除所有的葉子節(jié)點
重復(fù)如上過程直到整棵樹為空
示例

解題
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
評論
圖片
表情
