Sum Root to Leaf Numbers

题目描述: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.

   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; 
    	}
    } 
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值