您的位置:首页 > 其它

LeetCode: Recover Binary Search Tree

2012-12-06 03:57 393 查看
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?

Space O(n)的方法就是自己用stack来模拟inorder traverse ,然后将输出的结果存在一个vector里面,然后遍历vector找到冲突的对。

Space constant的方法就是用递归的方式进行inorder traverse,然后在遍历的过程中记录一个前驱节点,然后比较前驱节点和当前节点的值,将结果记录下来,最后交换一下就行了。

class Solution {
public:
TreeNode * inorderVisit(TreeNode *root, TreeNode *pre, vector<TreeNode *> &res){
if(root == NULL){return pre;}
TreeNode *last;
last = inorderVisit(root->left, pre, res);
if(last == NULL){
last = root;
}
if(root->val < last->val){
if(res[0] == NULL){
res[0] = last;
res[1] = root;
}
else{
res[1] = root;
}
}
last = inorderVisit(root->right, root, res);
return last == NULL? root : last;

}
void recoverTree(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (root == NULL) return;
vector<TreeNode *> res(2);
TreeNode *last = inorderVisit(root, NULL, res);
swap(res[0]->val, res[1]->val);
return;
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: