Skip to content

Commit 3358eee

Browse files
committed
add prob #538(2nd); iterative solution
1 parent 7faefd1 commit 3358eee

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#include <stack>
2+
using namespace std;
3+
4+
struct TreeNode {
5+
int val;
6+
TreeNode *left;
7+
TreeNode *right;
8+
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
9+
};
10+
11+
class Solution {
12+
public:
13+
TreeNode* convertBST(TreeNode* root) {
14+
if(NULL==root) return NULL;
15+
stack<TreeNode*> s_parent;
16+
stack<bool> s_visited;
17+
int res = 0;
18+
19+
s_parent.push(root);
20+
s_visited.push(false);
21+
while(!s_parent.empty()){
22+
TreeNode* tmp_node = s_parent.top(); s_parent.pop();
23+
bool tmp_visited = s_visited.top(); s_visited.pop();
24+
25+
if(tmp_visited){
26+
tmp_node->val += res;
27+
res = tmp_node->val;
28+
}
29+
else{
30+
//left
31+
if(tmp_node->left){
32+
s_parent.push(tmp_node->left);
33+
s_visited.push(false);
34+
}
35+
//self
36+
s_parent.push(tmp_node);
37+
s_visited.push(true);
38+
//right
39+
if(tmp_node->right){
40+
s_parent.push(tmp_node->right);
41+
s_visited.push(false);
42+
}
43+
}
44+
}
45+
46+
return root;
47+
}
48+
};

0 commit comments

Comments
 (0)