题目链接:https://leetcode.com/problems/sum-root-to-leaf-numbers/
Input: [1,2,3] 1 / \ 2 3 Output: 25 Explanation: The root-to-leaf path1->2
represents the number12
. The root-to-leaf path1->3
represents the number13
. Therefore, sum = 12 + 13 =25
.
思路,递归:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int ans=0;
public int sumNumbers(TreeNode root) {
if(root==null)
return ans;
helper(root,0);
return ans;
}
public void helper(TreeNode root,int sum){
sum=sum*10+root.val;
if(root.left==null&&root.right==null){
ans=ans+sum;
return;
}
if(root.left!=null)
helper(root.left,sum);
if(root.right!=null)
helper(root.right,sum);
}
}