129 Sum Root to Leaf Numbers

129. Sum Root to Leaf Numbers

1. Question

Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path1->2->3which represents the number123.

Find the total sum of all root-to-leaf numbers.

For example,

    1
   / \
  2   3

The root-to-leaf path1->2represents the number12. The root-to-leaf path1->3represents the number13.

Return the sum = 12 + 13 =25.

2. Implementation

(1) DFS recursion

class Solution {
    public int sumNumbers(TreeNode root) {
        return findSum(root, 0);
    }

    public int findSum(TreeNode node, int sum) {
        if (node == null) {
            return 0;
        }

        sum = 10 * sum + node.val;
        if (node.left == null && node.right == null) {
            return sum;
        }

        return findSum(node.left, sum) + findSum(node.right, sum);
    }
}

(2) BFS

3. Time & Space Complexity

DFS recursion: 时间复杂度: O(n), 空间复杂度: O(n)

BFS: 时间复杂度: O(n), 空间复杂度: O(w), w是树里有最多node的一层的node个数

Last updated

Was this helpful?