File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments