给定一个仅包含数字\ 0-9 0−9 的二叉树,每一条从根节点到叶子节点的路径都可以用一个数字表示。
例如根节点到叶子节点的一条路径是1\to 2\to 31→2→3,那么这条路径就用\ 123 123 来代替。
找出根节点到叶子节点的所有路径表示的数字之和
思想:利用树的前序遍历。
public class SumofTree {
public static void main(String[] args) {
TreeNode root=new TreeNode(1);
root.left=new TreeNode(2);
root.right=new TreeNode(3);
int sum=sumNumbers(root);
System.out.println(sum);
}
public static int sumNumbers (TreeNode root) {
// write code here
if(root==null)
return 0;
return calculate(root,0);
}
public static int calculate(TreeNode root,int sum){
if(root==null){
return 0;
}else{
sum=sum*10+root.val;
if(root.left==null && root.right==null) return sum;
return calculate(root.left,sum)+calculate(root.right,sum);
}
}
}
//定义树的节点
class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x){
this.val=x;
}
}