/**
* 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) {
findMaxDepth(root, 0);
findNumsInMaxDepth(root, 0);
return sum;
}
int sum = 0;
public void findNumsInMaxDepth(TreeNode node, int depth) {
if (node == null)
return;
findNumsInMaxDepth(node.left, depth + 1);
findNumsInMaxDepth(node.right, depth + 1);
// System.out.println(depth + " max: " + this.max + ": " + sum);
if (depth == max) {
this.sum += node.val;
}
}
int max = 0;
public void findMaxDepth(TreeNode node, int depth) {
if (node == null)
return;
findMaxDepth(node.left, depth + 1);
findMaxDepth(node.right, depth + 1);
this.max = Math.max(depth, this.max);
}
}