-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsumNumbers.cpp
More file actions
31 lines (31 loc) · 938 Bytes
/
sumNumbers.cpp
File metadata and controls
31 lines (31 loc) · 938 Bytes
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int sumNumbers(TreeNode* root) {
int ans = 0;
stack<pair<TreeNode*, int>> s;
s.push({root, root->val});
while(!s.empty()) {
auto [node, cur] = s.top();
s.pop();
if (!node->left && !node->right) {
ans += cur;
} else {
int t = cur * 10;
if (node->right) s.push({node->right, t + node->right->val});
if (node->left) s.push({node->left, t + node->left->val});
}
}
return ans;
}
};