Skip to content

Commit 573b366

Browse files
committed
add prob #257(2nd); iterative solution
1 parent 267b5ac commit 573b366

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed

257_Binary_Tree_Paths_2nd.cpp

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
/* iterative solution */
2+
3+
#include <string>
4+
#include <vector>
5+
#include <stack>
6+
using namespace std;
7+
8+
struct TreeNode {
9+
int val;
10+
TreeNode *left;
11+
TreeNode *right;
12+
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
13+
};
14+
15+
class Solution {
16+
public:
17+
vector<string> binaryTreePaths(TreeNode* root) {
18+
vector<string> res;
19+
if(root==NULL) return res;
20+
vector<int> nums;
21+
stack<TreeNode*> s_parent;
22+
stack<int> s_depth;
23+
stack<bool> s_visited;
24+
25+
s_parent.push(root);
26+
s_depth.push(1);
27+
s_visited.push(false);
28+
while(!s_parent.empty()){
29+
TreeNode* tmp_node = s_parent.top(); s_parent.pop();
30+
int tmp_depth = s_depth.top(); s_depth.pop();
31+
bool tmp_visited = s_visited.top(); s_visited.pop();
32+
33+
if(tmp_visited){
34+
while(tmp_depth<(int)nums.size()){
35+
nums.pop_back();
36+
}
37+
if((tmp_node->left==NULL)&&(tmp_node->right==NULL)){
38+
string tmp_str;
39+
for (int i = 0; i < (int)nums.size(); ++i) {
40+
if(i>0) tmp_str.append("->");
41+
int tmp_val = nums[i];
42+
if(tmp_val<0){
43+
tmp_val *= -1;
44+
tmp_str.push_back('-');
45+
}
46+
else if(tmp_val==0){
47+
tmp_str.push_back('0');
48+
continue;
49+
}
50+
51+
stack<char> s_char;
52+
while(tmp_val>0){
53+
s_char.push((tmp_val%10)+'0');
54+
tmp_val /= 10;
55+
}
56+
while(!s_char.empty()){
57+
tmp_str.push_back(s_char.top());
58+
s_char.pop();
59+
}
60+
}
61+
res.push_back(tmp_str);
62+
}
63+
}
64+
else{
65+
//right
66+
if(tmp_node->right){
67+
s_parent.push(tmp_node->right);
68+
s_depth.push(tmp_depth+1);
69+
s_visited.push(false);
70+
}
71+
//parent
72+
s_parent.push(tmp_node);
73+
s_depth.push(tmp_depth);
74+
s_visited.push(true);
75+
nums.push_back(tmp_node->val);
76+
//left
77+
if(tmp_node->left){
78+
s_parent.push(tmp_node->left);
79+
s_depth.push(tmp_depth+1);
80+
s_visited.push(false);
81+
}
82+
}
83+
}
84+
85+
return res;
86+
}
87+
};

0 commit comments

Comments
 (0)