Sum Root to Leaf Numbers

 

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path 1->2->3 which represents the number 123.

Find the total sum of all root-to-leaf numbers.

For example,

    1
   / \
  2   3

 

The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.

Return the sum = 12 + 13 = 25.

» Solve this problem

 

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     int sum;
12     public int sumNumbers(TreeNode root) {
13         // Start typing your Java solution below
14         // DO NOT write main() function
15         sum = 0;
16         int cur = 0;
17         add(root,cur);
18         return sum;
19     }
20     public void add(TreeNode node, int cur){
21         if(node == null){
22             return;
23         }
24         cur = cur * 10 + node.val;
25         if(node.left == null && node.right == null){//leaves
26             sum += cur;
27         }
28         add(node.left,cur);
29         add(node.right,cur);
30     }
31 }

 

posted on 2013-04-16 14:14  Step-BY-Step  阅读(128)  评论(0编辑  收藏  举报

导航