tree:恢复二叉搜索树

Leetcode, RecoverBinarySearchTree

#include 
#include 
#include 
using namespace std;

struct TreeNode
{
     
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {
      }
};

//Morris中序遍历 时间复杂度O(n),空间复杂度O(1)
vector<int> MorrisInOrder(TreeNode *root)
{
     
	vector<int> result;
	TreeNode *cur = root;
	while (cur != nullptr)
	{
     
		if (cur->left == nullptr)
		{
     
			result.push_back(cur->val);
			cur = cur->right;
		}
		else
		{
     
			//左子树最有子节点
			TreeNode *node = cur->left;
			while (node->right != nullptr && node->right != cur)
				node = node->right;
			if (node->right == nullptr)
			{
     
				node->right = cur;
				cur = cur->left;
			}
			else
			{
     
				result.push_back(cur->val);
				node->right = nullptr;
				cur = cur->right;
			}
		}
	}
	return result;
}

void detect(pair<TreeNode *, TreeNode *> &broken, TreeNode *prev, TreeNode *cur)
{
     
	if ( prev != nullptr && prev->val > cur->val )
	{
     
		if ( broken.first == nullptr)
		{
     
			broken.first = prev;
		}
		broken.second = cur;
	}
}

//Morris中序遍历 时间复杂度O(n),空间复杂度O(1)
void solution(TreeNode *root)
{
     
	pair<TreeNode *, TreeNode *> broken;
	TreeNode *prev = nullptr;
	TreeNode *cur = root;

	while (cur != nullptr)
	{
     
		if (cur->left == nullptr)
		{
     
			detect(broken, prev, cur);
			prev = cur;
			cur = cur->right;
		}
		else
		{
     
			//左子树最有子节点
			TreeNode *node = cur->left;
			while (node->right != nullptr && node->right != cur)
				node = node->right;
			if (node->right == nullptr)
			{
     
				node->right = cur;
				//prev = cur;	cur没有被访问
				cur = cur->left;
			}
			else
			{
     
				detect(broken, prev, cur);
				node->right = nullptr;
				prev = cur;
				cur = cur->right;
			}
		}
	}

	swap(broken.first->val, broken.second->val );
}

int main()
{
     
	{
     
		TreeNode *node1 = new TreeNode(1);
		TreeNode *node2 = new TreeNode(2);
		TreeNode *node3 = new TreeNode(3);
		node1->left = node3;
		node3->right = node2;
		auto vec = MorrisInOrder(node1);	//321
		solution(node1);
		vec = MorrisInOrder(node1);			//123
	}

	{
     
		TreeNode *node1 = new TreeNode(1);
		TreeNode *node2 = new TreeNode(2);
		TreeNode *node3 = new TreeNode(3);
		TreeNode *node4 = new TreeNode(4);
		node3->left = node1;
		node3->right = node4;
		node4->left = node2;
		auto vec = MorrisInOrder(node3);	//1324
		solution(node3);
		vec = MorrisInOrder(node3);			//1234
	}


	return 0;
}

你可能感兴趣的:(leet)