Thursday, August 14, 2014

Sum Root to Leaf Numbers

This question is not difficult. Based on DFS, value of each node is stored and summed up until leaf node is met. Once hit the leaf node, add value of this node, then add this result to resList. As soon as the whole tree is traversed, sum up all the elements in resList. Then we get what we want.


 /**  
  * Definition for binary tree  
  * public class TreeNode {  
  *   int val;  
  *   TreeNode left;  
  *   TreeNode right;  
  *   TreeNode(int x) { val = x; }  
  * }  
  */  
 public class Solution {  
   public int sumNumbers(TreeNode root) {  
     if(root == null) return 0;  
     LinkedList<Integer> resList = new LinkedList<Integer>();  
     sumRoot2Leaf(root,0,resList);  
     int res = 0;  
     for(Integer i:resList){  
       res+=i;  
     }  
     return res;  
   }  
   public void sumRoot2Leaf(TreeNode root, int res, LinkedList<Integer> resList){  
     if(root == null) return;  
     if(root.left == null && root.right == null){  
       res = res * 10 + root.val;  
       resList.add(res);  
       return;  
     }  
     sumRoot2Leaf(root.left,res*10 + root.val,resList);  
     sumRoot2Leaf(root.right,res*10 + root.val,resList);  
   }  
 }  

No comments:

Post a Comment