129. Sum Root to Leaf Numbers

输入: [1,2,3]
    1
   / \
  2   3
输出: 25
解释:
从根到叶子节点路径  代表数字 .
从根到叶子节点路径  代表数字 .
因此,数字总和 = 12 + 13 = 25

class Solution {

    public int sumNumbers(TreeNode root) {

        return sum(root, 0);

    }

    private int sum(TreeNode n, int s) {

        if (n == null)

            return 0;

        if (n.right == null && n.left == null)

            return s * 10 + n.val;

        return sum(n.left, s * 10 + n.val) + sum(n.right, s * 10 + n.val);

    }

}


posted @ 2019-03-15 11:57  MarkLeeBYR  阅读(84)  评论(0)    收藏  举报