题目:
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.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}"
.
解题思路:因为有两个节点被换,因此最多有两对节点逆序如:(3,2,1),找出这两对即(3,2)和(2,1),然后交换第一个和最后一个即可。有可能就一对逆序如中序遍历:(1,3,2),此时,交换3和2即可。
又如(5,30,8,15,20,6),此时,result里存的是(30,8,20,6)交换第一个和最后一个即变成(5,6,8,15,20,30)。
因此,其实最后的那个if-else可以用一句来代替:
swap(result.front()->val,result.back()->val);
或swap((*result.begin())->val,(*(result.end()-1))->val);
代码:
#include<iostream>
#include<vector>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void inorderTraverse(TreeNode *root,TreeNode *&parent,vector<TreeNode *> &result)
{
if(root==NULL)
return ;
inorderTraverse(root->left,parent,result);
// cout<<parent->val<<endl;
if(parent->val>root->val)
{
result.push_back(parent);
result.push_back(root);
}
parent=root;
inorderTraverse(root->right,parent,result);
}
void recoverTree(TreeNode *root)
{
TreeNode *parent=new TreeNode(INT_MIN);
vector<TreeNode *> result;
inorderTraverse(root,parent,result);
if(result.size()==2)
swap(result[0]->val,result[1]->val);
else
swap(result[0]->val,result[3]->val);
}
int main()
{
TreeNode* root=new TreeNode(3);
root->left=new TreeNode(2);
root->right=new TreeNode(1);
recoverTree(root);
system("pause");
return 0;
}