【leetcode】Recover Binary Search Tree

问题:

鉴于二叉搜索树。有两个节点不小心换位置,现在,我们需要修改。它不改变树的结构。

分析:

二叉排序树的遍历是有序。所以这个问题是建立在序模板的问题,所以我们可以先序,并配有pre指针指向当前遍历结果中的最后一个结点,即下次遍历前的前一个结点。然后就能够通过将当前结点与pre结点进行比較。来推断是否有序了。

若乱序。就将这两个结点都放入到预先定义的容器中。


错误的形式就这两种,我们看到,在乱序容器中,最多就存了四个元素。所以空间复杂度还是满足O(n)的,当然也能够用两个指针分别指向要进行调整的两个结点,如上图分别指向 2 和 1, 4 和 1.

实现:

//store disorder nodes, most of the number is 4.
vector<TreeNode*> outorder;
//point to the last node of inorder sequence
TreeNode *pre = NULL;
void visitInorder(TreeNode* root){
	
	if(root == NULL)
		return;
	
	if(root->left)
		visitInorder(root->left);
	
	if(pre == NULL)
		pre = root;

	else if(root->val < pre->val){

	    outorder.push_back(pre);
		outorder.push_back(root);
		
	}
	//move pre to the new tail.
	pre = root;
	if(root->right)
		visitInorder(root->right);
}

void recoverTree(TreeNode *root) {

	if( NULL == root )
		return;

	visitInorder(root);

	if(outorder.size())
	{
		swap(outorder[0]->val, outorder[outorder.size() - 1]->val);
	}
}


版权声明:本文博主原创文章,博客,未经同意不得转载。

原文地址:https://www.cnblogs.com/lcchuguo/p/4795601.html