LeetCode in Python 366. Find Leaves of Binary Tree
# 366. Find Leaves of Binary Tree
# Example:
# Given binary tree
# 1
# / \
# 2 3
# / \
# 4 5
# Returns [4, 5, 3], [2], [1].
class Solution(object):
ans = []
def findLeaves(self, root):
dfs(root)
return self.ans
def dfs(root):
if not root:
return 0
left = dfs(root.left)
right = dfs(root.right)
depth = max(left, right)
if depth == len(ans):
self.ans.append([root.val])
else:
self.ans[-1].append(root.val)
return depth+1
每次调用dfs函数,得到返回值的时候就是加入新解的时候,根据depth来判断这个解属于新的一层还是已有层。
此题的逻辑非常符合深度优先搜索的本质:到达叶子节点后逐级回溯