Sicily 1935 二叉树重建

数据结构的简单题,对帮助理解二叉树的遍历蛮有帮助的。


#include <iostream>
#include <cstring>

using namespace std;

struct node
{
	char val;
	node * left;
	node * right;
};

node * build(int n, char * pre, char * in)
{
    //注意strchr返回的是指向那个字符的指针,要减去头指针 
	if (n <= 0) return NULL;
	
	node * ans = new node;
	ans->val = pre[0];
	int order = strchr(in, pre[0]) - in;
	ans->left = build(order, pre+1, in);
	ans->right = build(n-order-1, pre+order+1, in+order+1);//这里不能用[],要用指针的加减法 
	
	
	return ans;
}

void BFS(node * root)
{
	if (root == NULL) return;
	
	node* q[30];//q是输出序列 
	q[0] = root;
	
	int n = 0, o = 1;//n代表输出节点数,o代表总结点数 
	
	while (n < o)
	{
		node * temp = q[n];
		n++;
		
		cout << temp->val;
		if (temp->left != NULL) q[o++] = temp->left;
		if (temp->right != NULL) q[o++] = temp->right;
	}
}

void deleteTree(node * root)
{
	if (root == NULL) return;
	if (root->left != NULL) deleteTree(root->left);
	if (root->right != NULL) deleteTree(root->right);
	delete root;
}

char preorder[30], inorder[30];
 
int main()
{
	int t;
	
	cin >> t;
	while (t --)
	{
		cin >> preorder >> inorder;
		int len = strlen(preorder);
		node * root = build(len, preorder, inorder);
		BFS(root);
		cout << endl; 
		deleteTree(root);
	}
	
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值