最近做PAT总是涉及二叉树的操作问题,现在来总结一下。。
已知前序中序,求后序和层次遍历
#include<stdio.h>
#include<stdlib.h>
#include<queue>
using namespace std;
typedef struct tree{
struct tree *l,*r;
int data;
}tree;
int pre[105],in[105];
tree* build(int *a,int *b,int c){
tree *t;
for(int i = 0;i<c;i++){
if(a[0] == b[i]){
t = (tree*) malloc(sizeof(tree));
t->data = a[0];
t->l = build(a+1,b,i);
t->r = build(a+i+1,b+i+1,c-i-1);
return t;
}
}
return NULL;
}
void postorder(tree* a){ //递归后序输出
if(a != NULL){
postorder(a->l);
postorder(a->r);
if(a->data == pre[0])
printf("%d\n",a->data);
else printf("%d ",a->data);
}
}
void leveltravel(tree *a){ //非递归层次遍历
queue<tree*> q;
tree* p = NULL;
if(a)
q.push(a);
while(!q.empty()){
p = q.front();
q.pop();
printf("%d ",p->data);
if(p->l)
q.push(p->l);
if(p->r)
q.push(p->r);
}
}
int main(){
int n;
tree* root;
while(~scanf("%d",&n)){
printf("输入前序:");
for(int i = 0;i<n;i++)
scanf("%d",pre+i);
printf("输入中序:");
for(int i = 0;i<n;i++)
scanf("%d",in+i);
root = build(pre,in,n);
tree* s = root;
printf("输出后序遍历:");
postorder(s);
printf("输出层次遍历:");
leveltravel(s);
}
return 0;
}
已知后序中序,求前序和层次遍历
#include<stdio.h>
#include<stdlib.h>
#include<queue>
using namespace std;
typedef struct tree{
struct tree *l,*r;
int data;
}tree;
int n,post[105],in[105],count;
tree* root;
tree* build(int *a,int *b,int c){
tree* t;
for(int i = 0;i<c;i++){
if(a[c-1] == b[i]){
t = (tree*) malloc(sizeof(tree));
t->data = a[c-1];
t->l = build(a,b,i);
t->r = build(a+i,b+i+1,c-i-1);
return t;
}
}
return NULL;
}
void preorder(tree *a){
if(a != NULL){
if(a->data == in[n-1])
printf("%d\n",a->data);
else printf("%d ",a->data);
preorder(a->l);
preorder(a->r);
}
}
void leveltravel(tree *a){
queue<tree*> q;
tree *p = NULL;
if(a)
q.push(a);
while(!q.empty()){
p = q.front();
q.pop();
printf("%d ",p->data);
if(p->l)
q.push(p->l);
if(p->r)
q.push(p->r);
}
}
int atLevel(tree *a,int x){
if(!a || x < 0)
return 0;
if(x == 0){
count++;
if(count == n)
printf("%d\n",a->data);
else printf("%d ",a->data);
return 1;
}
return atLevel(a->l,x-1)+atLevel(a->r,x-1);
}
void leveltravel2(tree *a){ //递归层次遍历
for(int i = 0; ;i++){
if(!atLevel(a,i))
break;
}
}
int main(){
while(~scanf("%d",&n)){
count = 0;
printf("输入后序:");
for(int i = 0;i<n;i++)
scanf("%d",post+i);
printf("输入中序:");
for(int i = 0;i<n;i++)
scanf("%d",in+i);
root = build(post,in,n);
tree *s = root;
printf("输出前序遍历:");
preorder(s);
printf("输出非递归层次遍历:");
leveltravel(s);
printf("\n");
printf("输出递归层次遍历:");
leveltravel2(s);
}
}