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