原题如下:
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.
void recoverTree0(TreeNode *root) {
vector<TreeNode *>v;
inOrder(root,v);
int i = 0;
for( i = 0; i < v.size(); i++){
if(v[i]->val > v[i + 1]->val)
break;
}
int j =v.size() - 1;
for(;j >0; j--){
if(v[j]->val < v[j - 1]->val)
break;
}
int temp = v[i]->val;
v[i]->val = v[j]->val;
v[j]->val = temp;
}
void inOrder(TreeNode *root,vector<TreeNode *>&v){
if(root == NULL)
return;
inOrder(root->left,v);
v.push_back(root);
inOrder(root->right,v);
}
思路二:在思路一的基础上,可以在不保存有序序列的情况下仅利用两个指针保存需要交换的节点,即在遍历的过程中用pre保存前一个节点,然后与当前节点比较,如果为第一个逆序,则让key1指向pre,key2指向当前遍历的节点root(此为应对仅有一个逆序的特殊情况),如果key1不为空,则为第二个逆序,key2指向当前节点root,此时即可提前结束遍历。
class Solution {
public:
TreeNode *key1 ,*key2 ,*pre;
void recoverTree(TreeNode *root) {
key1 = key2 = pre = NULL;
inOrder(root);
swap(key1->val,key2->val);
return;
}
void inOrder(TreeNode *root){
if(root == NULL)
return;
inOrder(root->left);
if(pre && pre->val > root->val){
if(key1 == NULL){
key1 = pre;
key2 = root;
}
else{
key2 = root;
return;
}
}
pre = root;
inOrder(root->right);
}
};
在手写出数列进行分析的情况下上题的思路就比较容易理解了,另外才发现C++提供了交换两个数的方法swap,还是要熟悉STL才行啊,还有就是类成员变量不能直接初始化(因为此时还没有内存空间),可以在构造函数以及成员方法中进行初始化。