Wednesday, February 25, 2015

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.
SolutionRecursion. Similar as [LeetCode] Binary Tree Maximum Path Sum Solution, the difference here is only adding a track variable to sum all the paths.
问题处理:
1 分情况就是: (1)空节点, (2)到了叶子节点, (3)一般节点(包括只有左孩子,只有右孩子,两个孩子都有)
2 递归到该点的时候就把这点的值与前面的值乘以10,然后相加
3 需要如何保存前面的值?以参数传递的方式保存,以供下一层使用。总值可以以两种方式保存:参数传递方式,返回函数值方式。
算法的本质是一次先序遍历,所以时间是O(n),空间是栈大小,O(logn)。
/**
 * 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) {
        return helper(root, 0);
    }
    
    public int helper(TreeNode root, int sum) {
        if(root == null) { //terminate condition, root == null, just return 0
            return 0;
        }
        
        if(root.left == null && root.right == null) { //terminate condition, if root == leaf, add the value to sum and return
            return sum * 10 + root.val;
        }
            
        return helper(root.left, sum*10+root.val) + helper(root.right, sum*10+root.val);
        
    }
}

No comments:

Post a Comment