L2-006 树的遍历

 

#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;
 } 

 

相关文章:

  • 2021-11-24
  • 2022-01-05
  • 2021-12-11
  • 2022-12-23
  • 2022-12-23
  • 2021-04-15
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-01-07
  • 2022-12-23
  • 2022-12-23
  • 2021-10-19
相关资源
相似解决方案