题目描述:
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Example 1:
Input: [1,3,null,null,2] 1 / 3 \ 2 Output: [3,1,null,null,2] 3 / 1 \ 2
Example 2:
Input: [3,1,4,null,null,2] 3 / \ 1 4 / 2 Output: [2,1,4,null,null,3] 2 / \ 1 4 / 3
Follow up:
- A solution using O(n) space is pretty straight forward.
- Could you devise a constant space solution?
算法实现:
我们可以看到,对BST进行中序遍历应该是升序排列,如果交换中序遍历中的相邻节点,那么中序排列中会出现一个非升序的两个节点,只需要交换这两个节点的值即可,比如[1,3,2,4]和[1,2,3,4];如果交换中序遍历中的非相邻节点,那么中序排列会出现两个非升序部分,只需要交换第一个部分的第一个节点的值和第二个部分的第二个节点的值即可,比如[1,5,3,4,2]和[1,2,3,4,5]
//鉴于上一个问题中对BST的定义,暂时不考虑左<=中<右的情况
/**
* 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 *one, *two, *forwardtree;
int flag = 1;
void recoverTree(TreeNode* root) {
finderror(root);
swap(one -> val, two -> val);
}
void finderror(TreeNode* root){
if(root == NULL)return;
finderror(root -> left);
if(forwardtree != NULL){
if(root -> val <= forwardtree -> val){
if(flag == 1){
one = forwardtree;
//可能会出现只有一次降序的情况,遇到这种情况只需要将降序的一对节点交换即可
two = root;
flag ++;
}
else if(flag > 1){
two = root;
return;
}
}
}
forwardtree = root;
finderror(root -> right);
}
};