Skip to content

Commit ae96f3f

Browse files
committed
Add O(1) space inorder traversal solution.
1 parent 2554d3f commit ae96f3f

File tree

1 file changed

+53
-1
lines changed

1 file changed

+53
-1
lines changed

Recover_Binary_Search_Tree.cc

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,4 +34,56 @@ class Solution {
3434
q->val = tmp;
3535
}
3636
}
37-
};
37+
};
38+
39+
//O(1) space solution
40+
//Based on Morris Traversal algorithm (Construct Threads Binary Tree)
41+
class Solution {
42+
public:
43+
void recoverTree(TreeNode *root) {
44+
// Start typing your C/C++ solution below
45+
// DO NOT write int main() function
46+
if (!root) return;
47+
TreeNode *pre = root;
48+
TreeNode *cur = root;
49+
TreeNode *tmp = NULL;
50+
TreeNode *One = NULL;
51+
TreeNode *Two = NULL;
52+
bool found = false;
53+
while (pre->left) pre = pre->left;
54+
while (cur) {
55+
if (!cur->left) {
56+
if (cur->val < pre->val) {
57+
if (!found) {
58+
found = true;
59+
One = pre;
60+
}
61+
Two = cur;
62+
}
63+
pre = cur;
64+
cur = cur->right;
65+
} else {
66+
tmp = cur->left;
67+
while (tmp->right && tmp->right != cur) {
68+
tmp = tmp->right;
69+
}
70+
if (!tmp->right) {
71+
tmp->right = cur;
72+
cur = cur->left;
73+
} else {
74+
tmp->right = NULL;
75+
if (cur->val < pre->val) {
76+
if (!found) {
77+
found = true;
78+
One = pre;
79+
}
80+
Two = cur;
81+
}
82+
pre = cur;
83+
cur = cur->right;
84+
}
85+
}
86+
}
87+
if (found) swap(One->val, Two->val);
88+
}
89+
};

0 commit comments

Comments
 (0)