您的位置:首页 > 其它

[leetcode] Recover Binary Search Tree

2013-08-19 15:49 417 查看
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?

confused what 
"{1,#,2,3}"
 means? >
read more on how binary tree is serialized on OJ.

二叉树中有两个节点swap了一下,现在需要你去纠正,题目中有个o(n)的算法,初步想法是可以对其进行先序遍历,然后将节点存储到一个数组中去,再遍历这个数组,找到两个反序了的数,将他们的值交换一下。

class Solution {
public:
void recoverTree(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
TreeNode **array=new TreeNode*[1000];
int count=0;
int p,q;
p=0,q=0;
putintoarray(root,array,count);
for(int i=1 ; i<count ; i++){
if(array[i-1]->val>array[i]->val)
swap(array[i-1]->val,array[i]->val);
}
for(int i=count-2 ; i>=0 ; i--){
if(array[i]->val>array[i+1]->val)
swap(array[i]->val,array[i+1]->val);
}
delete array;
}
void swap(int& a , int & b){
if(a==b)
return;
a=a^b;
b=a^b;
a=a^b;
}
void putintoarray(TreeNode *root , TreeNode **p, int& i){
if(!root)
return;
if(root->left)
putintoarray(root->left,p,i);
p[i++]=root;
if(root->right)
putintoarray(root->right,p,i);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: