LeetCode 129. 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.

example:
Input: [1,2,3]
1
/
2 3
Output: 25
Explanation:
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Therefore, sum = 12 + 13 = 25.

this following code is not correct, and it return the value which is 2X expected value.

class Solution {
    public int sumNumbers(TreeNode root) {
        if (root == null) return 0;
        return sumNumbers(root, 0);//
    }
    
    private int sumNumbers(TreeNode root, int sum) {
        if (root == null) return sum;
        return sumNumbers(root.left, sum * 10 + root.val) + sumNumbers(root.right, sum * 10 + root.val);
    }
}
//从高位到低位一个一个数字读的十进制值为:
//sum = sum * 10 + cur.val;

but another code works just fine:

class Solution {
    public int sumNumbers(TreeNode root) {
        return helper(root, 0);//
    }
    
    public int helper(TreeNode root, int sum){ //helper() not returning void but returnning int value;
        if(root == null) return 0; //we can't delete this too, it is important
        if(root.left == null && root.right == null){ //check if root is leaf
            return sum * 10 + root.val; //想一想为什么最后还要*10+val
        }
        return helper(root.left, sum*10 + root.val) + helper(root.right, sum*10 + root.val);//
    }
}
posted @ 2020-11-19 02:01  EvanMeetTheWorld  阅读(10)  评论(0)    收藏  举报