题目描述:
给你一棵二叉树的根节点 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
dfs代码如下:
/**
* 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 sum = 0;
public int deepestLeavesSum(TreeNode root) {
int maxDepth = depth(root);
dfs(root, 1, maxDepth);
return sum;
}
public void dfs(TreeNode root, int depth, int maxDepth) {
if (root == null) {
return;
}
if (depth == maxDepth) {
sum += root.val;
}
dfs(root.left, depth + 1, maxDepth);
dfs(root.right, depth + 1, maxDepth);
}
public int depth(TreeNode root) {
if (root == null) {
return 0;
}
return Math.max(depth(root.left), depth(root.right)) + 1;
}
}
bfs代码如下:
/**
* 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) {
if (root == null) {
return 0;
}
Queue<TreeNode> que = new LinkedList<>();
que.offer(root);
int ans = 0;
while (!que.isEmpty()) {
List<Integer> r = new ArrayList<>();
int size = que.size();
ans = 0;
for (int i = 0; i < size; i++) {
TreeNode t = que.poll();
ans += t.val;
if (t.left != null) {
que.offer(t.left);
}
if (t.right != null) {
que.offer(t.right);
}
}
}
return ans;
}
}
执行结果: