您的位置:首页 > 其它

二叉树 三种遍历构造二叉树+层次遍历 题目 PAT 树的遍历

2017-03-22 22:29 387 查看
https://www.patest.cn/contests/gplt/L2-006

1.后序遍历+中序遍历,构建二叉树。

2.队列层次输出二叉树

#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<string>
using namespace std;
int n;
int in[35],post[35];
struct node
{
int data;
node* lchil;
node* rchil;
}tree[35];
node* buildTree(int *in,int *post,int length)
{
//终止条件
if(length==0)return NULL;

//创建节点,最终返回得到root节点
node *root;
root = new node();
//后序遍历的最后一个节点,为根节点
root->data=*(post+length-1);

//pos中序遍历中找到与后序根节点相同的元素的下标
int pos=0;
while(in[pos]!=post[length-1])
pos++;
//递归建树
//格式(中序序列,后序序列,截断后长度)
root->lchil=buildTree(in,post,pos);
root->rchil=buildTree(in+pos+1,post+pos,length-pos-1);

return root;
}
void show(node *t)
{
queue<node*>q;
q.push(t);
int flag=0;
while(!q.empty())
{
node* tmp=q.front();
q.pop();
if(!flag)
{
cout<<tmp->data;
flag=1;
}
else
cout<<' '<<tmp->data;

if(tmp->lchil!=NULL)
q.push(tmp->lchil);
if(tmp->rchil!=NULL)
q.push(tmp->rchil);
}
cout<<endl;
}
int main()
{
while(cin>>n)
{
for(int i=0;i<n;++i)
cin>>post[i];
for(int i=0;i<n;++i)
cin>>in[i];
//1.
//构造二叉树 保存到root节点
//in是中序序列
//post是后序序列
//n是两种序列长度
node* root=buildTree(in,post,n);
//2.
//遍历bfs获得层次序列
show(root);
}
}
//前序遍历
void show(node* t)
{
if(t!=NULL)
{
cout<<t->data<<' ';
show(t->lchil);
show(t->rchil);
}
}
//中序遍历
void show(node* t)
{
if(t!=NULL)
{
show(t->lchil);
cout<<t->data<<' ';
show(t->rchil);
}
}
//后序遍历
void show(node* t)
{
if(t!=NULL)
{
show(t->lchil);
show(t->rchil);
cout<<t->data<<' ';
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐