一、题目描述
Given a binary tree containing digits from 0-9 only,
each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
Note: A leaf is a node with no children.
Example:
Input: [1,2,3]
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.
二、题解
方法一:求所有路径
- 递归求出所有的路径。
- 将每一条路径代表的数字计算出来。
- 返回总和。
List<List<Integer>> paths = null;
List<Integer> path = null;
public int sumNumbers(TreeNode root) {
paths = new ArrayList<>();
path = new ArrayList<>();
dfs(root);
int sum = 0;
for (int i = 0; i < paths.size(); i++) {
List<Integer> p = paths.get(i);
sum += getNum(p);
}
return sum;
}
//求出路径代表的数字
int getNum(List<Integer> path) {
int num = 0;
for (int i = 0; i < path.size(); i++) {
num = num * 10 + path.get(i);
}
return num;
}
//求出所有路径
void dfs(TreeNode root) {
if (root == null) {
return;
}
path.add(root.val);
if (root.left == null && root.right == null) {
paths.add(new ArrayList<>(path));
}
dfs(root.left);
dfs(root.right);
path.remove(path.size()-1);
}
复杂度分析
- 时间复杂度: ,
- 空间复杂度: ,
方法二:在遍历时计算(自顶向下)
- pre 记录上一次的数字大小,cur 记录当前层的数字大小。
- 当遍历到叶子结点时,表示路径已找到一条,累加路径的数字即可。
- 递归左子树,右子树。
* 注:第一次疏忽地提前结算了 sum,这样会导致 sum 多计算一次。
if (root == null) {
sum += pre;
return;
}
int sum;
public int sumNumbers(TreeNode root) {
dfs(root, 0);
return sum;
}
private void dfs(TreeNode root, int pre) {
if (root == null) {
return;
}
int cur = pre * 10 + root.val;
if (root.left == null && root.right == null) {
sum += cur;
return;
}
dfs(root.left, cur);
dfs(root.right,cur);
}
复杂度分析
- 时间复杂度: ,
- 空间复杂度: ,
方法三:栈迭代 | 队列迭代
...