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.

思路: 每个节点表示的值为  上一个节点的基数 * 10 + 该节点的值,用一个变量sum(base)来记录上一个节点的基数

java代码:

  1. int helper(TreeNode root,int sum) {
  2. if(root==null) return sum;
  3. if(root.left==null && root.right==null) {
  4. return sum * 10 + root.val;
  5. }
  6. int left = 0;
  7. int right = 0;
  8. if(root.left!=null) {
  9. left = helper(root.left,sum*10+root.val);
  10. }
  11. if(root.right!=null) {
  12. right = helper(root.right,sum*10+root.val);
  13. }
  14. return left + right;
  15. }
  16. public int sumNumbers(TreeNode root) {
  17. if(root==null) return 0;
  18. if(root.left==null && root.right==null) return root.val;
  19. return helper(root,0);
  20. }
posted @ 2014-07-25 17:37  purejade  阅读(78)  评论(0)    收藏  举报