Simple Java Solution (recursive) 2ms.


  • 0
    public int sumNumbers(TreeNode root) {
    	   return getPaths(root,new StringBuffer(),0);
        }
        
         int getPaths(TreeNode root, StringBuffer sb, int sum)
    	 {
    		 if(root == null)
    			 return sum;
    		 sb.append(root.val);
    		 if(root.left == null && root.right == null)
    		 {
    		     sum += Integer.parseInt(sb.toString());
    		 }
    		 sum = getPaths(root.left,sb,sum);
    		 sum = getPaths(root.right,sb,sum);
    		 sb.deleteCharAt(sb.length() -1);
    		 return sum;
    	 }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.