https://leetcode.com/problems/sum-root-to-leaf-numbers/description/
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
.
package go.jacob.day810;
/**
* 129. Sum Root to Leaf Numbers
*
* @author Jacob
*
*/
public class Demo1 {
public int sumNumbers(TreeNode root) {
if (root == null)
return 0;
int sum = 0;
return sumNumbers(root, sum);
}
private int sumNumbers(TreeNode root, int sum) {
if (root == null)
return 0;
if (root.left == null && root.right == null)
return sum * 10 + root.val;
return sumNumbers(root.left, 10 * sum + root.val) +
sumNumbers(root.right, 10 * sum + root.val);
}
/*
* My Solution
*/
private int sumNumbers_1(TreeNode root, int sum) {
sum += root.val;
int leftSum = 0;
int rightSum = 0;
if (root.left != null)
leftSum = sumNumbers(root.left, 10 * (sum));
if (root.right != null)
rightSum = sumNumbers(root.right, 10 * (sum));
// 如果root的左右子树为空,返回sum。否则返回左右子树递归的结果和
return root.left == null && root.right == null ? sum : leftSum + rightSum;
}
}