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.

原问题链接:https://leetcode.com/problems/sum-root-to-leaf-numbers/

问题分析

  这个问题的要求比较有意思,因为它要计算所有从根到叶节点构成的值,并且要将它们所有的和计算出来。从根节点到叶节点的过程相当于一个10进制的过程,每下一层,就对前面的值乘以十再加上当前层的值。

  那么在实现中我们就需要想办法求到从根节点到叶节点最终形成的值。对树中间任意节点来说,我们就需要有一个对应的位置保存有到这个节点的值,然后对于它的子节点就可以用这个当前值再乘以十再相加了。为了得到这最终形成的值,我们需要对树做一个遍历,这样才能保证覆盖到所有的节点。在遍历的过程中,我们判断出所有左右子树节点都为空的节点才算是叶节点。现在的问题就是要选择哪种树遍历的方法了。我们可以选择树的层次化遍历方法,用一个队列,不断的将队列里的元素取出来,然后将它所有存在的子节点加入到队列中。前面也提到过,对应的节点也需要有一个对应的值,我们可以用另外一个队列和它同步的保存对应的值。这样每次从节点队列里取元素出来的时候,我们也取对应的值队列里的元素。如果当前节点的左右子树为空,则它符合条件,我们将它累加到一个全局的变量中。如果它有非空的节点,则将这个节点对应的值乘以十再加那个节点的值,并将这个值加入到值队列中。

  按照这个思路,我们得到的详细实现如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int sumNumbers(TreeNode root) {
        if(root == null) return 0;
        int sum = 0;
        Queue<Integer> numQueue = new LinkedList<>();
        Queue<TreeNode> nodeQueue = new LinkedList<>();
        numQueue.add(root.val);
        nodeQueue.add(root);
        while(!nodeQueue.isEmpty()) {
            TreeNode node = nodeQueue.remove();
            int num = numQueue.remove();
            if(node.left == null && node.right == null) {
                sum += num;
                continue;
            }
            if(node.left != null) {
                nodeQueue.add(node.left);
                numQueue.add(num * 10 + node.left.val);
            }
            if(node.right != null) {
                nodeQueue.add(node.right);
                numQueue.add(num * 10 + node.right.val);
            }
        }
        return sum;
    }
}

猜你喜欢

转载自shmilyaw-hotmail-com.iteye.com/blog/2308854