MrainW's Home

All things come to those who wait!

0%

LeetCode 129. Sum Root to Leaf Numbers

Question

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.

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

Solution

  • Solution1 – DFS, top down
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
int sum = 0;
public int sumNumbers(TreeNode root) {
if (root == null)
return 0;
dfs(root, 0);
return sum;
}
private void dfs(TreeNode root, int num){
num = num * 10 + root.val;
if (root.left == null && root.right == null){
sum += num;
return;
}
if (root.left != null) dfs(root.left, num);
if (root.right != null) dfs(root.right, num);
}
}
1
2
3
4
5
top down general steps:
1. base case(leaf)
2. 利用父问题传下来的值做计算 num = 10*num + num
3. 额外操作
4. 把值传给子问题递归 dfs()

Complexity:

Time complexity: O(n)

Space complexity: O(h)

Welcome to my other publishing channels