129. Sum Root to Leaf Numbers

2018-04-07  本文已影响3人  衣介书生

题目分析

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.

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
   public int sumNumbers(TreeNode root) {
        return helper(root, 0);
    }
    
    public int helper(TreeNode root, int sum) {
        if(root == null) {
            return 0;
        }
        // 当前层是最后一层,返回上一层的值的10倍加上自身
        if(root.left == null && root.right == null) {
            return sum * 10 + root.val;
        }
        // 如果还有下一层,将上一层的值扩大10倍再加上自身传到下一层
        return helper(root.left, sum * 10 + root.val) + helper(root.right, sum * 10 + root.val);
    }
}
上一篇下一篇

猜你喜欢

热点阅读