二叉树遍历

1302.层数最深叶子节点的和

难度中等132收藏分享切换为英文接收动态反馈

给你一棵二叉树的根节点 root ,请你返回 层数最深的叶子节点的和

示例 1:

img

1
2
输入:root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
输出:15

示例 2:

1
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int deepestLeavesSum(TreeNode root) {
int ans = 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
int temp = 0;
for (int i = queue.size(); i > 0; i--) {
TreeNode node = queue.poll();
temp += node.val;
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
ans = temp;
}
return ans;
}
}

image-20220817215229769


1302.层数最深叶子节点的和
http://example.com/2022/08/17/leetcode每日一题/1302.层数最深叶子节点的和/
作者
madao33
发布于
August 17, 2022
许可协议