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?
修正二叉排序树中的一个错误对,不改变树结构。
中序遍历一下,找到逆序的两个地方,交换值就行了,题目要求constant space solution,反正就是把数组改成两个变量,在遍历过程中记录,
差不多,懒得改了。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void dfs(TreeNode* root,vector<TreeNode*> &path)
{
if(!root) return ;
dfs(root->left,path);
path.push_back(root);
dfs(root->right,path);
}
void recoverTree(TreeNode* root) {
vector<TreeNode*> path;
dfs(root,path);
int st=0,en=path.size()-1;
while(st<en)
{
if(path[st]->val<path[st+1]->val)
st++;
else if(path[en]->val>path[en-1]->val)
en--;
else
{
swap(path[en]->val,path[st]->val);
return ;
}
}
}
};