[leetcode] Recover Binary Search Tree

本文介绍了一种解决二叉搜索树中两个节点错误交换位置的方法。通过先序遍历找到并修正错误节点,确保树结构不变。同时探讨了如何在不使用额外空间的情况下解决问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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?

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

二叉树中有两个节点swap了一下,现在需要你去纠正,题目中有个o(n)的算法,初步想法是可以对其进行先序遍历,然后将节点存储到一个数组中去,再遍历这个数组,找到两个反序了的数,将他们的值交换一下。

class Solution {
public:
    void recoverTree(TreeNode *root) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
		TreeNode **array=new TreeNode*[1000];
		int count=0;
		int p,q;
		p=0,q=0;
		putintoarray(root,array,count);
		for(int i=1 ; i<count ; i++){
			if(array[i-1]->val>array[i]->val)
				swap(array[i-1]->val,array[i]->val);
		}
		for(int i=count-2 ; i>=0 ; i--){
			if(array[i]->val>array[i+1]->val)
				swap(array[i]->val,array[i+1]->val);
		}
		delete array;
	}
	void swap(int& a , int & b){
		if(a==b)
			return;
		a=a^b;
		b=a^b;
		a=a^b;
	}
	void putintoarray(TreeNode *root , TreeNode **p, int& i){
		if(!root)
			return;
		if(root->left)
			putintoarray(root->left,p,i);
		p[i++]=root;
		if(root->right)
			putintoarray(root->right,p,i);
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值