[GeeksForGeeks] Sum all of the numbers formed from root to leaf paths

Given a binary tree, where every node value is a number . Find the sum of all the numbers which are formed from root to leaf paths.

For example consider the following Binary Tree.
 

           6                               
         /   \                          
        3     5                      
      /   \     \
     2    5      4             
        /  \                        
       7    4                 
            
  There are 4 leaves, hence 4 root to leaf paths:
  Path                      Number
  6->3->2                   632
  6->3->5->7                6357
  6->3->5->4                6354
  6->5>4                    654   
Answer = 632 + 6357 + 6354 + 654 = 13997 


Solution 1. Pre order tree traversal using recursion
 1 class TreeNode {
 2     int val;
 3     TreeNode left, right;
 4     TreeNode(int v) {
 5         this.val = v;
 6         this.left = null;
 7         this.right = null;
 8     }
 9 }
10 public class SumAllPaths {
11     private int sum = 0;
12     public int sumAllPathsFromRootToLeaf(TreeNode root) {
13         helper(root, 0);
14         return sum;
15     }
16     private void helper(TreeNode curr, int currVal) {
17         if(curr == null){
18             return;
19         }
20         if(curr.left == null && curr.right == null) {
21             sum += currVal * 10 + curr.val;
22             return;
23         }
24         helper(curr.left, currVal * 10 + curr.val);
25         helper(curr.right, currVal * 10 + curr.val);
26     }
27 }

 

Follow up question: can you do it without using recursion?

posted @ 2017-08-16 03:25  Review->Improve  阅读(210)  评论(0编辑  收藏  举报