# 题目

```输入: [1,2,3]
1
/ \
2   3

```输入: [4,9,0,5,1]
4
/ \
9   0
/ \
5   1

# 题解

1. 先遍历根节点；
2. 遍历左子树，遍历左子树的时候，把走当前路径的数字带到左子树的求解中；
3. 遍历右子树，遍历右子树的时候，把走当前路径的数字带到右子树的求解中；
4. 更新总的和。
```class Solution {
private int sum = 0;
private void helper(TreeNode node, int father) {
if (node == null) return ;
int current = father * 10 + node.val;
if (node.left == null && node.right == null) {
sum += current;
return;
}
helper(node.left, current);
helper(node.right, current);
}

public int sumNumbers(TreeNode root) {
if (root == null) return sum;
helper(root, 0);
return sum;
}
}```

```class Solution {
public int sumNumbers(TreeNode root) {
int sum = 0;
if (root == null) return sum;
Stack<TreeNode> nodeStack = new Stack<>();
Stack<Integer> numStack = new Stack<>();
while (!nodeStack.isEmpty()) {
TreeNode current = nodeStack.pop();
Integer currentNum = numStack.pop() * 10 + current.val;
if (current.left == null && current.right == null) {
sum += currentNum;
}
if (current.left != null) {
}
if (current.right != null) {
}
}
return sum;
}
}```

```public class Solution {
public int sumNumbers(TreeNode root) {
if(root == null) return 0;
int res = 0;
while(!queue.isEmpty()) {
int size = queue.size();
// 把该层的都入队，同时如果遇到叶节点，计算更新
while(size-- > 0) {
root = queue.poll();
int val = numQueue.poll() * 10 + root.val;
if(root.left == null && root.right == null)
res += val;
if(root.left != null) {
}
if (root.right != null) {
}
}
}
return res;
}
}```

79 篇文章17 人订阅

0 条评论