[LeetCode] 129. Sum Root to Leaf Numbers

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:
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:
Example 2
Input: root = [4,9,0,5,1]
Output: 1026
Explanation:
The root-to-leaf path 4->9->5 represents the number 495.
The root-to-leaf path 4->9->1 represents the number 491.
The root-to-leaf path 4->0 represents the number 40.
Therefore, sum = 495 + 491 + 40 = 1026.

Constraints:
The number of nodes in the tree is in the range [1, 1000].
0 <= Node.val <= 9
The depth of the tree will not exceed 10.

求根到叶子节点数字之和。

给你一个二叉树的根节点 root ,树中每个节点都存放有一个 0 到 9 之间的数字。 每条从根节点到叶节点的路径都代表一个数字:

例如,从根节点到叶节点的路径 1 -> 2 -> 3 表示数字 123 。
计算从根节点到叶节点生成的 所有数字之和 。

叶节点 是指没有子节点的节点。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/sum-root-to-leaf-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

思路是前序遍历。记录一个变量 sum 存之前所有的加和,当遍历到当前节点的时候,sum *= 10 再加当前的节点值 cur.val。

复杂度

时间O(n)
空间O(n)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int res = 0;

public int sumNumbers(TreeNode root) {
helper(root, 0);
return res;
}

private void helper(TreeNode root, int sum) {
if (root == null) {
return;
}
sum = sum * 10 + root.val;
if (root.left == null && root.right == null) {
res += sum;
return;
}
helper(root.left, sum);
helper(root.right, sum);
}
}

JavaScript实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* @param {TreeNode} root
* @return {number}
*/
var sumNumbers = function (root) {
if (root == null) {
return 0;
}
var total = 0;
helper(root, 0);
return total;

function helper(root, sum) {
if (root == null) {
return;
}
sum = sum * 10 + root.val;
if (root.left == null && root.right == null) {
total += sum;
return;
}
helper(root.left, sum);
helper(root.right, sum);
}
};

相关题目

1
2
129. Sum Root to Leaf Numbers
1022. Sum of Root To Leaf Binary Numbers

[LeetCode] 129. Sum Root to Leaf Numbers
https://shurui91.github.io/posts/3006640849.html
Author
Aaron Liu
Posted on
March 22, 2020
Licensed under