129. Sum Root to Leaf Numbers
Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path1->2->3which represents the number123.
Find the total sum of all root-to-leaf numbers.
For example,
1
/ \
2 3
The root-to-leaf path1->2represents the number12.
The root-to-leaf path1->3represents the number13.
Return the sum = 12 + 13 =25.
Analysis:
Regular tree recursive traverse, when reach a null node, we add the sum of that path to final result.
Complexity:
Time: O(N)
Space: O(logn)
Code:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int returnSum = 0;
public int sumNumbers(TreeNode root) {
if(root == null)
{
return 0;
}
sum(root, 0);
return returnSum;
}
private void sum(TreeNode root, int s)
{
if(root == null)
{
return;
}
if(root.left == null && root.right == null)
{
returnSum += root.val + s*10;
return;
}
int tempSum = s*10 + root.val;
sum(root.left, tempSum);
sum(root.right, tempSum);
}
}