题目:
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? //还没想到
分析:本质中序遍历序列是排序的。
当前值比前一个值小时,若还没找到第一个数,则前一个值就是第一个发生逆序的值;若已经找到第二个数,则当前值就是第二个发生逆序的值。
/**
* 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 recoverTree(TreeNode* root) {
if (NULL == root || NULL == root->left && NULL == root->right) return;
stack<TreeNode *> sta;
TreeNode *p = root;
bool foundFirst = false;//是否已找到第一个逆序元素
TreeNode *lastNode = NULL;
TreeNode *nextNode = NULL;//用于处理当中序遍历序列相邻两个元素交换的情况
TreeNode *p1 = NULL, *p2 = NULL;
while (p != NULL || !sta.empty()){
while (p != NULL){
sta.push(p);
p = p->left;
}
TreeNode *q = sta.top();
sta.pop();
if (lastNode != NULL && q->val < lastNode->val){
if (!foundFirst){
p1 = lastNode;
nextNode = q;
foundFirst = true;
}
else if(lastNode != p1){
p2 = q;
break;
}
}
lastNode = q;
p = q->right;
}
if (NULL == p2) p2 = nextNode;
int tmp = p1->val;
p1->val = p2->val;
p2->val = tmp;
}
};