Skip to content

Commit 376f1ac

Browse files
committed
add prob #1022; iterative solution
1 parent 573b366 commit 376f1ac

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
Given a binary tree, each node has value 0 or 1.  Each root-to-leaf path represents a binary number starting with the most significant bit.  For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13.
3+
4+
For all leaves in the tree, consider the numbers represented by the path from the root to that leaf.
5+
6+
Return the sum of these numbers.
7+
8+
Note:
9+
10+
The number of nodes in the tree is between 1 and 1000.
11+
node.val is 0 or 1.
12+
The answer will not exceed 2^31 - 1.
13+
14+
来源:力扣(LeetCode)
15+
链接:https://leetcode-cn.com/problems/sum-of-root-to-leaf-binary-numbers
16+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
17+
*/
18+
19+
#include <stack>
20+
using namespace std;
21+
22+
struct TreeNode {
23+
int val;
24+
TreeNode *left;
25+
TreeNode *right;
26+
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
27+
};
28+
29+
class Solution {
30+
public:
31+
int sumRootToLeaf(TreeNode* root) {
32+
if(NULL==root) return 0;
33+
int res = 0;
34+
stack<TreeNode*> s_parent;
35+
stack<int> s_sum;
36+
37+
s_parent.push(root);
38+
s_sum.push(0);
39+
while(!s_parent.empty()){
40+
TreeNode* tmp_node = s_parent.top(); s_parent.pop();
41+
int tmp_sum = s_sum.top(); s_sum.pop();
42+
tmp_sum = (tmp_sum<<1) + tmp_node->val;
43+
44+
if((tmp_node->left==NULL)&&(tmp_node->right==NULL)){
45+
res += tmp_sum;
46+
continue;
47+
}
48+
if(tmp_node->right){
49+
s_parent.push(tmp_node->right);
50+
s_sum.push(tmp_sum);
51+
}
52+
if(tmp_node->left){
53+
s_parent.push(tmp_node->left);
54+
s_sum.push(tmp_sum);
55+
}
56+
}
57+
58+
return res;
59+
}
60+
};

0 commit comments

Comments
 (0)