Skip to content

Commit 3a90c5c

Browse files
1022. Sum of Root To Leaf Binary Numbers.cpp
1 parent edab0dd commit 3a90c5c

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
//Runtime: 4 ms, faster than 95.02% of C++ online submissions for Sum of Root To Leaf Binary Numbers.
2+
//Memory Usage: 17.5 MB, less than 20.00% of C++ online submissions for Sum of Root To Leaf Binary Numbers.
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* struct TreeNode {
7+
* int val;
8+
* TreeNode *left;
9+
* TreeNode *right;
10+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11+
* };
12+
*/
13+
class Solution {
14+
public:
15+
int sumRootToLeaf(TreeNode* root) {
16+
int sum = 0;
17+
stack<TreeNode*> stk;
18+
TreeNode* cur;
19+
map<TreeNode*, TreeNode*> parent;
20+
21+
stk.push(root);
22+
parent[root] = nullptr;
23+
24+
while(!stk.empty()){
25+
cur = stk.top(); stk.pop();
26+
if(!cur->left && !cur->right){
27+
int path_val = 0, h = 0 ;
28+
while(cur != nullptr){
29+
path_val += (cur->val << h);
30+
h++;
31+
cur = parent[cur];
32+
}
33+
// cout << path_val << endl;
34+
sum += path_val;
35+
continue;
36+
}
37+
if(cur->right){
38+
stk.push(cur->right);
39+
parent[cur->right] = cur;
40+
}
41+
if(cur->left){
42+
stk.push(cur->left);
43+
parent[cur->left] = cur;
44+
}
45+
}
46+
47+
return sum;
48+
}
49+
};

0 commit comments

Comments
 (0)