![]() |
#2
流照君2019-07-13 15:08
|
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2
就是给出二叉树的后序和中序
求出二叉树的层次遍历

#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
const int inf=105;
int in[inf],post[inf],n;
struct node{
int data;
struct node * lchild;
struct node * rchild;
};
void bfs(node * root)
{
queue<node*> q;
q.push(root);
while(!q.empty())
{
node *p=q.front();
cout<<p->data<<" ";
q.pop();
if(p->lchild !=NULL)
q.push(p->lchild);
if(p->rchild !=NULL)
q.push(p->rchild);
}
}
node * creat_tree(int postl,int postr,int inl,int inr)
{
if(postl<postr)
return NULL;
node * root=new node;
root->data=post[postr];
int i=postl;
while(i<inr)
{
if(post[postr]==in[i])
break;
i++;
}
int num=i-inl;//左子树节点个数
root->lchild=creat_tree(postl,postr+num-1,inl,i-1);
root->rchild=creat_tree(postr+num,postr-1,i+1,inr);
return root;
}
int main()
{
cin>>n;
for(int i=0;i<n;i++)
cin>>post[i];
for(int i=0;i<n;i++)
cin>>in[i];
node * root=creat_tree(0,n-1,0,n-1);
bfs(root);
return 0;
}
#include<algorithm>
#include<queue>
using namespace std;
const int inf=105;
int in[inf],post[inf],n;
struct node{
int data;
struct node * lchild;
struct node * rchild;
};
void bfs(node * root)
{
queue<node*> q;
q.push(root);
while(!q.empty())
{
node *p=q.front();
cout<<p->data<<" ";
q.pop();
if(p->lchild !=NULL)
q.push(p->lchild);
if(p->rchild !=NULL)
q.push(p->rchild);
}
}
node * creat_tree(int postl,int postr,int inl,int inr)
{
if(postl<postr)
return NULL;
node * root=new node;
root->data=post[postr];
int i=postl;
while(i<inr)
{
if(post[postr]==in[i])
break;
i++;
}
int num=i-inl;//左子树节点个数
root->lchild=creat_tree(postl,postr+num-1,inl,i-1);
root->rchild=creat_tree(postr+num,postr-1,i+1,inr);
return root;
}
int main()
{
cin>>n;
for(int i=0;i<n;i++)
cin>>post[i];
for(int i=0;i<n;i++)
cin>>in[i];
node * root=creat_tree(0,n-1,0,n-1);
bfs(root);
return 0;
}
不知道为什么出现段错误???
求大神来解答