1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
private int ans;

public int sumNumbers(TreeNode root) {
int ans = 0;
Deque<Pair<TreeNode, Integer>> stack = new ArrayDeque<>();
stack.push(new Pair(root, 0));
while (!stack.isEmpty()) {
Pair<TreeNode, Integer> currPair = stack.pop();
TreeNode currNode = currPair.getKey();
int currNum = currPair.getValue();
if (currNode != null) {
currNum = currNum * 10 + currNode.val;
if (currNode.left == null && currNode.right == null) {
ans += currNum;
} else {
stack.push(new Pair(currNode.left, currNum));
stack.push(new Pair(currNode.right, currNum));
}
}
}
return ans;
}
}

ζ₯θ‡ͺ129钘.