作业帮 > 综合 > 作业

已知某二叉树的前序序列及中序序列.要求输出其后序序列,试写出程序.

来源:学生作业帮 编辑:拍题作业网作业帮 分类:综合作业 时间:2024/04/28 05:06:16
已知某二叉树的前序序列及中序序列.要求输出其后序序列,试写出程序.
输入树的节点,输入0结束
1 2 3 4 5 6 7 8 9 0
中序打印
1->2->3->4->5->6->7->8->9->
后序打印
9->8->7->6->5->4->3->2->1->
前序打印
1->2->3->4->5->6->7->8->9->
//////////////////////////////////////////////////////////////////////////////////////////
#include<stdlib.h>
#include<stdio.h>
typedef struct tree
{
struct tree *left;
int date;
struct tree *right;
}treenode,*b_tree;
///////按顺序插入节点/////////////////////
b_tree insert(b_tree root,int node)
{
b_tree newnode;
b_tree currentnode;
b_tree parentnode;
newnode=(b_tree)malloc(sizeof(treenode));
newnode->date=node;
newnode->right=NULL;
newnode->left=NULL;
if(root==NULL)
return newnode;
else
{
currentnode=root;
while(currentnode!=NULL)
{
parentnode=currentnode;
if(currentnode->date>node)
currentnode=currentnode->left;
else
currentnode=currentnode->right;
}
if(parentnode->date>node)
parentnode->left=newnode;
else
parentnode->right=newnode;
}
return root;
}
//////建立树///////////////////
b_tree creat(int *date,int len)
{
b_tree root=NULL;
int i;
for(i=0;i<len;i++)
root=insert(root,date[i]);
return root;
}
//////中序打印////////////////
void print1(b_tree root)
{if(root!=NULL)
{
print1(root->left);
printf("%d->",root->date);
print1(root->right);
}
}
//////后序打印////////////////
void print2(b_tree root)
{if(root!=NULL)
{
print2(root->left);
print2(root->right);
printf("%d->",root->date);
}
}
//////前序打印////////////////
void print3(b_tree root)
{if(root!=NULL)
{ printf("%d->",root->date);
print3(root->left);
print3(root->right);
}
}
///////测试函数//////////////////
void main()
{
b_tree root=NULL;
int i,index;
int value;
int nodelist[20];
printf("输入树的节点,输入0结束\n");
index=0;
scanf("%d",value);
while(value!=0)
{
nodelist[index]=value;
index=index+1;
scanf("%d",value);
}
root=creat(nodelist,index);
printf("\n中序打印\n");
print1(root);
printf("\n后序打印\n");
print2(root);
printf("\n前序打印\n");
print3(root);}