构建二叉树

构建二叉树

  • 前序遍历,后序遍历,层次遍历都是提供根结点的信息,中序遍历用来区分左右子树。
  • 中序遍历和前,中,层次任一组合都可以完全确定一颗二叉树,无中序遍历一定无法唯一确定一颗二叉树。
//由后序遍历和中序遍历建树,打印层次遍历 
//详见算法笔记
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
//后,中
int n;
struct node{
	int data;
	node *lchild,*rchild;
}; 
int post[35],in[35];

node* build(int posts,int poste,int ins,int ine){// [],[]左右均为闭区间 
	if(posts>poste)return NULL;
	
	int k;
	for(k=ins;k<=ine;k++)
		if(post[poste]==in[k])
			break;
	//k=3
	node* root=new node;  //注意,这里要新建节点,不能直接node* root; 
 	
	root->data=post[poste];
	
	int numleft=k-ins;
	
	root->lchild=build(posts,posts+numleft-1,ins,k-1);
	
	root->rchild=build(posts+numleft,poste-1,k+1,ine);
	
	return root;
}
queue<node*> que;
void print(node* root){
	
	if(root)que.push(root);//注意判断非空,不然段错误 
	else return;
	bool f=0;
	
	while(!que.empty()){
		node* temp=que.front();que.pop();
		if(f)cout<<" ";
		cout<<temp->data;f=1;
		if(temp->lchild)//注意判断非空,不然段错误 
		que.push(temp->lchild);
		if(temp->rchild)
		que.push(temp->rchild);
	} 
}
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* root=build(0,n-1,0,n-1);
	print(root);
}
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值