tree:由先序和中序遍历建立二叉树

Leetcode, Construct Binary Tree from Preorder and Inorder Traversal

#include <iostream>
#include <vector>
#include <stack>
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> MorrisIn(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;
}

template <typename InputIter>
TreeNode *buildTree(InputIter pre_first, InputIter pre_last, InputIter in_first, InputIter in_last)
{
	if (pre_first == pre_last)	return nullptr;
	if (in_first == in_last)	return nullptr;

	auto root = new TreeNode(*pre_first);

	auto inRootPos = find(in_first, in_last, *pre_first);
	auto leftSize = distance(in_first, inRootPos);

	root->_left = buildTree(next(pre_first), next(pre_first, leftSize + 1), in_first, next(in_first + leftSize));
	root->_right = buildTree(next(pre_first, leftSize + 1), pre_last, next(in_first, leftSize + 1), in_last);

	return root;
}

//时间复杂度O(n), 空间复杂度O(logn)
TreeNode *solution(vector<int> &preorder, vector<int> &inorder)
{
	return buildTree(preorder.begin(), preorder.end(), inorder.begin(), inorder.end());
}

int main()
{
#if 0
	TreeNode *node1 = new TreeNode(1);
	TreeNode *node2 = new TreeNode(2);
	TreeNode *node3 = new TreeNode(3);
	TreeNode *node4 = new TreeNode(4);
	TreeNode *node5 = new TreeNode(5);
	TreeNode *node6 = new TreeNode(6);
	TreeNode *node7 = new TreeNode(7);
	node1->_left = node2;
	node1->_right = node3;
	node2->_left = node4;
	node2->_right = node5;
	node3->_left = node6;
	node3->_right = node7;
#endif // 0

	vector<int> preorder = {1,2,4,5,3,6,7};
	vector<int>	inorder = { 4,2,5,1,6,3,7};
	auto node = solution(preorder, inorder);
	auto vec = MorrisIn(node);	//4251637

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值