题目:基础题,代码里给出了三种解答方法,其中Morris法是O(1)space。
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Note:A solution using O( n ) space is pretty straight forward. Could you devise a constant space solution?
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
//recursion 方法:
TreeNode* first;
TreeNode* second;
TreeNode* pre;
void recoverTree(TreeNode* root) {
inorder(root);
int temp = first->val;
first->val = second->val;
second->val = temp;
}
void inorder(TreeNode* root){
if(root == NULL) return ;
inorder(root->left);
if(pre != NULL && pre->val >= root->val){
if(first == NULL) //这里经过vs2013验证 如果没有对first初始化, 那么其值为NULL
first = pre;
second = root;
}
pre = root;
inorder(root->right);
}
//stack 方法:
void recoverTree(TreeNode* root) {
TreeNode* first = NULL;
TreeNode* second = NULL;
TreeNode* pre = NULL;
TreeNode* cur = root;
stack<TreeNode*> s;
while(!s.empty() || cur)
{
if(cur)
{ //visit curr's left subtree
s.push(cur);
cur = cur->left;
}else{//done left subtree of curr Node
cur = s.top();
s.pop();
//visit root and do something
if(pre != NULL && pre->val >= cur->val){
if(first == NULL)
first = pre;
second = cur;
}
pre = cur;
//visit curr's right subtree
cur = cur->right;
}
}
int temp = first->val;
first->val = second->val;
second->val = temp;
}
//Morris 方法
void recoverTree(TreeNode* root) {
TreeNode* first = NULL;
TreeNode* second = NULL;
TreeNode* pre = NULL;
TreeNode* pred = NULL;
TreeNode* cur = root;
while(cur != NULL)
{
if(pre != NULL && pre->val >= cur->val){
if(first == NULL)
first = pre;
second = cur;
}
if(cur->left != NULL){
//find cur's predecessor
pred = cur->left;
while(pred->right != NULL && pred->right != cur) pred = pred->right;
if(pred->right != cur){
pred->right = cur;
cur = cur->left;
}else{
pred->right = NULL;
//visit
pre = cur;
cur = cur->right;
}
}else{//visit
pre = cur;
cur = cur->right;
}
}
int temp = first->val;
first->val = second->val;
second->val = temp;
}
};
详解: