LeetCode 129. Sum Root to Leaf Numbers
2020-05-20 21:42:40 # leetcode

Problem

LeetCode 129. Sum Root to Leaf Numbers

1. 题目简述

给出一棵只含有value值为0-9的二叉树,根节点为root,每一条从root到leaf节点的路径都代表一个数字,求这些所有数字之和。例如:

Input: [4,9,0,5,1]
    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.

2. 算法思路

DFS

很简单的DFS的思路,前序遍历的思路,到达根节点时做一次判断。

3. 解法

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
37
/**
* 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) {
dfs(root, 0);
return res;
}

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

dfs(root.left, currSum);
dfs(root.right, currSum);
}
}