给定一个只包含 0-9 数字的二叉树,每个根到叶的路径可以代表一个数字。
例如,从根到叶路径 1->2->3则代表数字 123。
查找所有根到叶数字的总和。
例如,
1
/ \
2 3
根到叶子路径 1->2 表示数字 12。
根到叶子路径 1->3 表示数字 13。
返回总和 = 12 + 13 = 25。
详见:https://leetcode.com/problems/sum-root-to-leaf-numbers/description/
Java实现:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int sumNumbers(TreeNode root) {
if(root==null){
return 0;
}
return helper(root,0);
}
private int helper(TreeNode root,int sum){
if(root==null){
return 0;
}
if(root.left==null&&root.right==null){
return sum*10+root.val;
}
return helper(root.left,sum*10+root.val)+helper(root.right,sum*10+root.val);
}
}