首页 > 其他 > 详细

构建一棵二叉树并按照层次遍历输出

时间:2014-04-07 02:21:11      阅读:427      评论:0      收藏:0      [点我收藏+]

这个算法中的构建一棵二叉树用的是前序和中序来构建二叉树的。

层次遍历当然要用到队列了。

#include<iostream>
#include<malloc.h>
#include<queue>
#include<list>
using namespace std;
struct node
{
	char c;
	node *lchild,*rchild;
};
char pre[100],mid[100];
void build(node* &t,int start1,int end1,int start2,int end2)
{
	int i=start2;
	while(pre[start1]!=mid[i])
		i=i+1;
	t=(node*)malloc(sizeof(node));
	t->c=pre[start1];
	if(i==start2)
		t->lchild=NULL;
	else build(t->lchild,start1+1,start1+i-start2,start2,i-1);
	if(i==end2)
		t->rchild=NULL;
	else build(t->rchild,start1+i-start2+1,end1,i+1,end2);
}
list<node*> que;
void visit(node *t)
{
	que.push_back(t);
	while(!que.empty())
	{
		node *temp=que.front();
		cout<<temp->c;
		if(temp->lchild!=NULL)
			que.push_back(temp->lchild);
		if(temp->rchild!=NULL)
			que.push_back(temp->rchild);
		que.pop_front();
	}
	cout<<endl;
}
void last(node *t)
{
	if(t==NULL)
		return;
	if(t->lchild!=NULL)
		last(t->lchild);
	if(t->rchild!=NULL)
		last(t->rchild);
	cout<<t->c;
}
int main()
{
	node *tree;
	int length;
	while(1==1)
	{
		cout<<"pre"<<endl;
		cin>>pre;
		cout<<"mid"<<endl;
		cin>>mid;
		length=strlen(pre);
		build(tree,0,length-1,0,length-1);
		//last(tree);
        if(!que.empty())
			que.clear();
		visit(tree);
	}
	return 0;
}




构建一棵二叉树并按照层次遍历输出,布布扣,bubuko.com

构建一棵二叉树并按照层次遍历输出

原文:http://blog.csdn.net/killer_in_silence/article/details/23046307

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!