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?
二叉排序树中有两个节点被交换了,要求把树恢复成二叉排序树。
最简单的办法,中序遍历二叉树生成序列,然后对序列中排序错误的进行调整。最后再进行一次赋值操作。
但这种方法要求n的空间复杂度,题目中要求空间复杂度为常数,所以需要换一种方法。
递归中序遍历二叉树,设置一个pre指针,记录当前节点中序遍历时的前节点,如果当前节点大于pre节点的值,说明需要调整次序。
/**
* 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:
TreeNode*p,*q;
TreeNode*pre;
public:
void inorder(TreeNode* root)
{
if(root->left) inorder(root->left);
if(pre!=NULL && pre->val>root->val)
{
if(p==NULL) p = pre;
q = root;
}
pre = root;
if(root->right) inorder(root->right);
}
void recoverTree(TreeNode* root) {
p = q = pre = NULL;
inorder(root);
swap(p->val, q->val);
}
};