前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >L2-006 树的遍历

L2-006 树的遍历

作者头像
用户2965768
发布2019-03-11 14:47:02
3150
发布2019-03-11 14:47:02
举报
文章被收录于专栏:wymwym
代码语言:javascript
复制
#include <bits/stdc++.h>
using namespace std;
//2 3 1 5 7 6 4 后序 
//1 2 3 4 5 6 7 中序 
struct node{
	int n;
	node *lc,*rc;
};
int in[35],post[35],n; 
node * create(int pl,int pr,int inl,int inr)
{
	int i; 
	if(pl > pr)return NULL;
	
	node * tp = new node();
	tp->n = post[pr];
	
	//找到中序遍历中对应根节点的值 
	for(i=inl;i<=inr;i++)
	if(in[i]==post[pr])break; 
	
	int num = i - inl - 1;//该根结点左子树结点个数 
	
	tp->lc = create(pl, pl+num, inl, i-1);
	tp->rc = create(pl+num+1, pr-1, i+1, inr);
	
	return tp;
}
void print(node *a)
{
	queue<node *> q;
	while(!q.empty())q.pop();
	q.push(a);
	while(!q.empty())
	{
		node *t = q.front();
		q.pop();
		if(t==a)printf("%d",t->n);
		else
		printf(" %d",t->n);
		if(t->lc)q.push(t->lc);
		if(t->rc)q.push(t->rc);
	}
}
int main()
{
	scanf("%d",&n);
	for(int i=0; i<n ; i++){
		scanf("%d",&post[i]);
	}
	for(int i=0; i<n ;i++){
		scanf("%d",&in[i]);
	}
	node* head = create(0,n-1,0,n-1);
	print(head); 
	
	return 0;
 } 
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年02月28日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档