首页 > 代码库 > leetcode--Sum Root to Leaf Numbers

leetcode--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.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    /**This problem is just an implementation of bfs<br>
     *The algorithm is straightforward:<br>
     * @author Averill Zheng
     * @version 2014-06-02
     * @since JDK 1.7
     */
    public int sumNumbers(TreeNode root) {
        int sum = 0;
        Queue<TreeNode> node = new LinkedList<TreeNode>();
        Queue<Integer> number = new LinkedList<Integer>();
        if(root != null){
            node.add(root);
            number.add(root.val);
            while(node.peek() != null){
                TreeNode aNode = node.poll();
                int num = number.poll();
                if(aNode.left != null){
                    node.add(aNode.left);
                    number.add(num * 10 +aNode.left.val);
                }
                if(aNode.right != null){
                    node.add(aNode.right);
                    number.add(num * 10 +aNode.right.val);
                }
                if(aNode.left == null && aNode.right == null){
                    sum += num;
                }
            }
        }
        return sum;    
    }
}