Skip to content

Commit af1b1bd

Browse files
authored
Add files via upload (doocs#332)
1 parent 6fb4279 commit af1b1bd

File tree

1 file changed

+34
-0
lines changed
  • solution/0100-0199/0129.Sum Root to Leaf Numbers

1 file changed

+34
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+
* };
9+
*/
10+
class Solution {
11+
public:
12+
int sumNumbers(TreeNode* root) {
13+
if (!root) return 0;
14+
int res = 0;
15+
stack<TreeNode*> st{{root}};
16+
while (!st.empty()) {
17+
TreeNode* t = st.top();
18+
st.pop();
19+
if (!t->left && !t->right) {
20+
res += t->val;
21+
}
22+
if (t->right) {
23+
t->right->val += t->val * 10;
24+
st.push(t->right);
25+
}
26+
if (t->left) {
27+
t->left->val += t->val * 10;
28+
st.push(t->left);
29+
}
30+
}
31+
return res;
32+
}
33+
34+
};

0 commit comments

Comments
 (0)