【题目】
给你一棵二叉树的根节点 root ,请你返回 层数最深的叶子节点的和 。
示例 1:
输入:root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
输出:15
示例 2:
输入:root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
输出:19
提示:
树中节点数目在范围 [1, 104] 之间。
1 <= Node.val <= 100
【代码】
【方法1:迭代】
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def deepestLeavesSum(self, root: TreeNode) -> int:
if not root:
return 0
queue=[root]
ans=0
while queue:
sz=len(queue)
ans=0
for _ in range(sz):
root=queue.pop(0)
ans+=root.val
if root.left:
queue.append(root.left)
if root.right:
queue.append(root.right)
return ans
【方法2-递归】
class Solution:
def visit(self,root,dep):
if not root:
return
self.nums[dep]=self.nums.setdefault(dep,[])
self.nums[dep].append(root.val)
self.visit(root.left,dep+1)
self.visit(root.right,dep+1)
def deepestLeavesSum(self, root: TreeNode) -> int:
self.dep=0
self.nums={}
self.visit(root,1)
return sum(self.nums.popitem()[1])
【方法3-递归】
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def visit(self,root,dep):
if not root:
return
if dep==self.dep:
self.num+=root.val
elif dep>self.dep:
self.num=root.val
self.dep=dep
self.visit(root.left,dep+1)
self.visit(root.right,dep+1)
def deepestLeavesSum(self, root: TreeNode) -> int:
self.dep=1
self.num=0
self.visit(root,1)
return self.num