题目描述: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.
(给一个二叉树只包含数字0——9,每根叶路径可以表示一个数。
一个例子是根到叶路径1 - > 2 - 3,代表数字123。
查找所有根到叶数的总数。)
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.
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.
(给一个二叉树只包含数字0——9,每根叶路径可以表示一个数。
一个例子是根到叶路径1 - > 2 - 3,代表数字123。
查找所有根到叶数的总数。)
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.
public class Sum_Root_to_Leaf_Numbers {
public static int record=0;
public static void Sum(TreeNode tree,int sum)
{
if(tree!=null)
{
//到叶子节点时
if(tree.left==null&&tree.right==null)
{
//sum是每条路径上面的和,而record是总和
sum=sum*10+tree.value;
record+=sum;
}
else
{
//遍历左右子树
Sum(tree.left,sum*10+tree.value);
Sum(tree.right,sum*10+tree.value);
}
}
}
public static void main(String[] args) {
TreeNode t1=new TreeNode(1);
TreeNode t2=new TreeNode(2);
TreeNode t3=new TreeNode(3);
TreeNode t4=new TreeNode(4);
TreeNode t5=new TreeNode(5);
TreeNode t6=new TreeNode(6);
TreeNode t7=new TreeNode(7);
TreeNode t8=new TreeNode(8);
t1.left=t2;
t1.right=t3;
// t2.right=t4;
t2.left=t4;
t2.right=t5;
t4.right=t7;
t3.left=t6;
t3.right=t8;
Sum(t1,0);
System.out.println(record);
}
}
class TreeNode
{
int value;//该点的值
TreeNode left;//左节点
TreeNode right;//右节点
TreeNode(int x)
{
if(x>=0&&x<=9)
{
value = x;
}
}
}