99. Recover Binary Search Tree
1 | /** |
S(n) : O(logn)
由inorder的顺序来看,很神奇,找规律
1 | Nice work. However, I think it'd better to make this part more clear: the number of times that you will find prev.val >= root.val depends on whether the two nodes that get swapped are next to each other in the sequence of in-order traversal. |
1 | How do we find these two elements? For example, we have the following tree that is printed as in order traversal: |
迭代实现 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void recoverTree(TreeNode* root) {
TreeNode* first = nullptr, *second = nullptr, *prev = nullptr, *cur = root;
stack<TreeNode*> s;
while(!s.empty() || cur)
{
while(cur)
{
s.push(cur);
cur = cur->left;
}
cur = s.top();
s.pop();
if(prev && prev->val > cur->val)
{
if(!first)
first = prev;
if(first)
second = cur;
if(prev != first)
break;
}
prev = cur;
cur = cur->right;
}
swap(first->val, second->val);
}
};
https://leetcode.com/problems/recover-binary-search-tree/discuss/32559/Detail-Explain-about-How-Morris-Traversal-Finds-two-Incorrect-Pointer