Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- Given a binary tree, return the sum of values of its deepest leaves
- * Definition for a binary tree node.
- * public class TreeNode {
- * int val;
- * TreeNode left;
- * TreeNode right;
- * TreeNode(int x) { val = x; }
- * }
- */
- class Solution {
- private static int sum, maxPathCount;
- public int deepestLeavesSum(TreeNode root) {
- sum = 0;
- if(root == null){
- return sum;
- }
- maxPathCount = 0;
- int currPathCount = 0;
- traverse(currPathCount,root);
- return sum;
- }
- private void traverse(int currPathCount,TreeNode currNode){
- if(currNode.left == null && currNode.right == null){
- currPathCount++;
- if(maxPathCount < currPathCount){
- maxPathCount = currPathCount;
- sum = currNode.val;
- }else if(maxPathCount == currPathCount){
- sum += currNode.val;
- }
- }else{
- currPathCount++;
- if(currNode.left != null){
- traverse(currPathCount, currNode.left);
- }
- if(currNode.right != null){
- traverse(currPathCount, currNode.right);
- }
- return;
- }
- return;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement