【LeetCode】99. Recover Binary Search Tree

Recover Binary Search Tree

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?

基本知识点:二叉搜索树的中序遍历就是升序序列。

因此不满足升序的两个点就是互换的地方。设置头结点INT_MIN来保证第一次满足。

问题在于,不满足升序的地方最多一共会出现4次,例如:

INT_MIN, 4, 2, 3, 1, 5

>      >

涉及到4,2,3,1

稍作分析即可知道,第一次出现反常(>)意味着前一个结点有问题,而第二次出现反常(<)

意味着后一个结点有问题。因此交换这两个问题节点即可。

有个小问题需要注意:如果一共只有两个节点,那么两次反常在同一次比较中出现了。

为了处理这种情况,我们在第一次反常时,就把后一个结点也设置为问题节点,后续再不断更新。

/**
* 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* first;
TreeNode* second;
TreeNode* prev;
int last;
void recoverTree(TreeNode* root) {
first = NULL;
second = NULL;
prev = NULL;
last = INT_MIN;
inorder(root);
swap(first->val, second->val);
}
void inorder(TreeNode* root)
{
if(root == NULL)
return;
inorder(root->left);
if(root->val < last)
{
if(first == NULL)
first = prev;
second = root;
}
prev = root;
last = root->val;
inorder(root->right);
}
};

【LeetCode】99. Recover Binary Search Tree

上一篇:ibatis的there is no statement named xxx in this SqlMap


下一篇:[LeetCode] Validate Binary Search Tree (两种解法)