首页 > 编程语言 > 详细

[Leetcode][JAVA] Sum Root to Leaf Numbers

时间:2014-10-27 08:07:28      阅读:400      评论:0      收藏:0      [点我收藏+]

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.

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.

 

最开始把这题当回溯法题目做了,就是收集所有的路径和,然后加起来。后来发现其实如果到了叶子节点后把值传给上层就成了类似分治法的方法,代码也比较简洁:

 1     public int sumNumbers(TreeNode root) {
 2          return sumN(root,0);
 3     }
 4     public int sumN(TreeNode nd, int v)
 5     {
 6         if(nd==null)
 7             return 0;
 8         if(nd.left==null && nd.right==null)
 9             return v*10+nd.val;
10         return sumN(nd.left, v*10+nd.val)+sumN(nd.right, v*10+nd.val);
11     }

 

如果不上传值到上层,就用一个变量保存总和, 代码如下:

 1     public int sumNumbers(TreeNode root) {
 2          sumN(root,0);
 3          return sum;
 4     }
 5     int sum=0;
 6     public void sumN(TreeNode nd, int v)
 7     {
 8         if(nd==null)
 9             return;
10         if(nd.left==null && nd.right==null)
11             sum += v*10+nd.val;
12         sumN(nd.left, v*10+nd.val);
13         sumN(nd.right, v*10+nd.val);
14     }

 

另外,使用栈进行DFS可以非递归地实现,代码比较复杂没有实现。。

[Leetcode][JAVA] Sum Root to Leaf Numbers

原文:http://www.cnblogs.com/splash/p/4053373.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!