您的位置:首页 > 其它

[LeetCode] Recover Binary Search Tree

2012-11-19 19:50 337 查看
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?

这题用O(n)的辅助空间比较好做,中序遍历后排个序O(nlogn)。但要不改变树的结构来完成就比较难了。

我只能想到一个把bst转为double link list后排序,再转为bst的方法,但转为bst就没法保证依然是原来bst的结构了。

/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
vector<int> val;
vector<TreeNode* > index;
public:
void traverse(TreeNode *node)
{
if (node == NULL)
return;

traverse(node->left);
val.push_back(node->val);
index.push_back(node);
traverse(node->right);
}

void recoverTree(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
traverse(root);
sort(val.begin(), val.end());
for(int i = 0; i < val.size(); i++)
index[i]->val = val[i];
}
};


空间O(1)

/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void treeWalk(TreeNode* root, TreeNode*& prv, TreeNode*& first, TreeNode*& second)
{
if(root==NULL)
return;
treeWalk(root->left,prv,first,second);
if((prv!=NULL)&&(prv->val>root->val)){
if(first==NULL)
first=prv;
second=root;
}
prv=root;
treeWalk(root->right,prv,first,second);
}

void recoverTree(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
TreeNode* first=NULL;
TreeNode* second=NULL;
TreeNode* prv=NULL;
treeWalk(root,prv,first,second);
int tmp=first->val;
first->val=second->val;
second->val=tmp;
}
};


空间O(1)

class Solution {
public:
void treeWalk(TreeNode* root, TreeNode*& prv, TreeNode*& first, TreeNode*& second)
{
if(root==NULL)
return;
treeWalk(root->left,prv,first,second);
if((prv!=NULL)&&(prv->val>root->val)){
if(first==NULL)
first=prv;
second=root;
}
prv=root;
treeWalk(root->right,prv,first,second);
}

void recoverTree(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
TreeNode* first=NULL;
TreeNode* second=NULL;
TreeNode* prv=NULL;
treeWalk(root,prv,first,second);
int tmp=first->val;
first->val=second->val;
second->val=tmp;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: