LeetCode 99. Recover Binary Search Tree

You are given the root of a binary search tree (BST), where exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.

Follow up: A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?

Example 1:

Input: root = [1,3,null,null,2]
Output: [3,1,null,null,2]
Explanation: 3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid.






Input: root = [3,1,4,null,null,2]
Output: [2,1,4,null,null,3]
Explanation: 2 cannot be in the right subtree of 3 because 2 < 3. Swapping 2 and 3 makes the BST valid.

实现思路:

题意就是二叉搜索树中有一个结点放错了位置,一般BST的题,都是利用了它最重要的一条性质,就是中序遍历后是一个有序序列。所以可以明白如果有一个结点放错了位置,那么中序遍历后,会有两个结点的位置是不在正确位置上的,给一个图:

可以发现当7放错后,那么我们只需要定义x和y指针,找到错误位置的两个结点进行交换即可,也可以视作树的双指针。

AC代码:

class Solution {
		vector<TreeNode*> sq;
	public:
		void dfs(TreeNode *root) {
			if(root==nullptr) return;
			dfs(root->left);
			sq.push_back(root);
			dfs(root->right);
		}
		void swap(TreeNode *a,TreeNode *b) {
			int temp=a->val;
			a->val=b->val;
			b->val=temp;
		}

		void recoverTree(TreeNode* root) {
			dfs(root);
			int x=-1,y=-1,size=sq.size(),tag=0;//存储位置错误的结点位置
			for(int i=0; i<size-1; i++) {
				if(sq[i]->val>sq[i+1]->val) {
					if(!tag) {//两种情况  第一种
						tag=1;
						x=i;
					} else y=i+1;//保留第二个逆序的位置
				}
			}
			if(x!=-1&&y==-1) swap(sq[x],sq[x+1]);
			else swap(sq[x],sq[y]);
		}
};
posted @ 2021-03-11 19:42  coderJ_ONE  阅读(34)  评论(0编辑  收藏  举报