129. Sum Root to Leaf Numbers

Leetcode

https://leetcode.com/problems/sum-root-to-leaf-numbers/arrow-up-right

題目

You are given the root of a binary tree containing digits from 0 to 9 only.

Each root-to-leaf path in the tree represents a number.

  • For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123.

Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer.

A leaf node is a node with no children.

Example 1:

Input: root = [1,2,3]
Output: 25
Explanation:
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Therefore, sum = 12 + 13 = 25.

Example 2:

解答

  • 方法一

Recursion

Runtime: 70 ms, faster than 75.20% of JavaScript online submissions for Sum Root to Leaf Numbers.

Memory Usage: 42 MB, less than 84.83% of JavaScript online submissions for Sum Root to Leaf Numbers.

  • 方法二

Iteration

Runtime: 64 ms, faster than 90.68% of JavaScript online submissions for Sum Root to Leaf Numbers.

Memory Usage: 42.6 MB, less than 39.49% of JavaScript online submissions for Sum Root to Leaf Numbers.

Last updated