您的位置:首页 > 大数据 > 人工智能

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 a

2016-05-19 14:34 387 查看
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class Solution {
public int sumNumbers(TreeNode root) {
if(root==null)return 0;
return sumRoot(root,0);
}

private int sumRoot(TreeNode root, int sum) {
if(root==null)return 0;
sum=sum*10+root.val;//关键
if(root.left==null&&root.right==null)return sum;
return sumRoot(root.left, sum)+sumRoot(root.right, sum);//左右都要递归哦
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: