2016/11/10 1001. 二叉树重建

参考:http://blog.csdn.net/yong369044325/article/details/7901008

用递归方法,先找出根节点,然后分左右进行递归重建。注意根节点要按引用传递。

广度优先遍历则用队列实现。根节点入队,队不空时,先对队前访问,并弹出,若左不空,则左子树入队,右子树同样。

#include <iostream>
#include <string>
#include <list>
using namespace std;
class Node
{
public:
	Node(char a = '0')
	{
		v = a;
		left = nullptr;
		right = nullptr;
	}
	Node *left;
	Node *right;
	char v;
};
void Rebuilt(string pre, string in, int length, Node** root)
{
	if (!pre.length() && !in.length())
	{
		return;
	}
	Node* p = new Node(pre[0]);
	if (*root == nullptr)
	{
		*root = p;
	}
	if (length == 1)
	{
		return;
	}
	int pos = in.find(pre[0]);
	int leftL = pos;
	int rightL = length - pos - 1;
	if (leftL > 0)
	{
		Rebuilt(pre.substr(1), in, leftL, &((*root)->left));
	}
	if (rightL > 0)
	{
		Rebuilt(pre.substr(leftL + 1), in.substr(leftL + 1), rightL, &((*root)->right));
	}
}
int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		string a, b;
		Node* root = nullptr;
		cin >> a >> b;
		Rebuilt(a, b, a.length(), &root);
		list<Node*> LL;
		LL.push_back(root);
		while (!LL.empty())
		{
			Node* p = LL.front();
			LL.pop_front();
			cout << p->v ;
			if (p->left != nullptr)
			{
				LL.push_back(p->left);
			}
			if (p->right != nullptr)
			{
				LL.push_back(p->right);
			}
		}
		cout << endl;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值