您的位置:首页 > 其它

Sum Root to Leaf Numbers

2015-02-18 03:16 155 查看
https://oj.leetcode.com/problems/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.

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 int sumNumbers(TreeNode root)

一般这种跟path相关然后又必须收集齐全所有Path内容的题目大致上考虑的就是top-down或者bottom-up这两种做法。这一题相对来说比较适合top-down的做法,第一件要做的事情就是将每一个Path变成一个数字。第二件要做的事情就是把它们加一起。下面给出的第一种做法是基于top-down的。这里有一个trick就是top-down其实需要一个全局变量或者一个引用,在c++里面一个reference的参数可以解决这个问题,但是在java就木有这个办法了。所以就用了另一个解决方案,请参考代码好了,顺便感谢code
ganker,这个方案是来自于他的文章:

public int sumNumbers(TreeNode root) {
if(root == null)
return 0;
ArrayList<Integer> res = new ArrayList<Integer>();
res.add(0);
helper(0, res, root);
return res.get(0);
}

public void helper(int cur_num, ArrayList<Integer> res, TreeNode root){
if(root.left == null && root.right == null){
res.set(0, res.get(0) + cur_num * 10 + root.val);
}else{
cur_num = cur_num * 10 + root.val;
if(root.left != null)
helper(cur_num, res, root.left);
if(root.right != null)
helper(cur_num, res, root.right);
}
}


实际上如果你希望在递归里面保留一个值可以随时操作,这样得一个ArrayList<Integer>的元素会是一个类中全局变量的很好的替代品。但是如果你不想这么做,下面这段代码便是top-down遍历数字然后bottom-up回收结果的一个做法,同样值得参考:

public int sumNumbers(TreeNode root) {
return top_to_bot(0, root);
}
public int top_to_bot(int cur_num, TreeNode root){
if(root == null){
return 0;
}
int cur_level_num = cur_num * 10 + root.val;
if(root.left == null && root.right == null)
return cur_level_num;
return top_to_bot(cur_level_num, root.left) + top_to_bot(cur_level_num, root.right);
}

下面给一个bfs的算法:

public int sumNumbers(TreeNode root) {
Queue<TreeNode> bfsQueue = new LinkedList<TreeNode>();
Queue<Integer> resultQueue = new LinkedList<Integer>();
Integer result = 0;
if(root == null)
return result;
bfsQueue.add(root);
resultQueue.add(root.val);
while(!bfsQueue.isEmpty()){
int curNumber = resultQueue.poll();
TreeNode curNode = bfsQueue.poll();
if(curNode.left == null && curNode.right == null)
result += curNumber;
if(curNode.left != null){
resultQueue.add(curNumber * 10 + curNode.left.val);
bfsQueue.add(curNode.left);
}
if(curNode.right != null){
resultQueue.add(curNumber * 10 + curNode.right.val);
bfsQueue.add(curNode.right);
}
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: