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

Note: A leaf is a node with no children.

129. Sum Root to Leaf Numbers

方法思路

class Solution {
    //Memory Usage: 36.7 MB, less than 85.40%
    //Runtime: 0 ms, faster than 100.00%
    public int sumNumbers(TreeNode root) {
        return sum(root, 0);
    }
    public int sum(TreeNode node, int x){
        if(node == null) return 0;
        if(node.left == null && node.right == null)
            return node.val + x * 10;
        int left = sum(node.left, node.val + x * 10);
        int right = sum(node.right, node.val + x * 10);
        return left + right;
    }
}