美文网首页
129. Sum Root to Leaf Numbers

129. Sum Root to Leaf Numbers

作者: 衣介书生 | 来源:发表于2018-04-07 21:03 被阅读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);
        }
    }
    

    相关文章

      网友评论

          本文标题:129. Sum Root to Leaf Numbers

          本文链接:https://www.haomeiwen.com/subject/zowucftx.html