数据结构,我想创建一颗任意的二叉树,不一定是完全二叉树,不知道应该如何操作

2025-02-28 07:01:36
推荐回答(1个)
回答1:

这个是输入结点个数和和树的先序中序构造二叉树
#include
#include
#define NULL 0
typedef struct node
{
int data;
node *left;
node *right;
}node;

node *CreateTree(int *pre,int *in,int n)
{
if(n==0)
return NULL;
node *root;
root=(node *)malloc(sizeof(node));
root->data=pre[0];
int i=0;
while(in[i]!=pre[0])
i++;
root->left=CreateTree(pre+1,in,i);
root->right=CreateTree(pre+i+1,in+i+1,n-i-1);
return root;
}
void Print(node *root)
{
if(root!=NULL)
{
printf("%d ",root->data);
Print(root->left);
Print(root->right);
}
return;
}
void main()
{
int n,pre[20],in[20],post[20],i;
printf("type in the number of the node of the tree\n");
scanf("%d",&n);
printf("type in the pre order of the tree\n");
for(i=0;i scanf("%d",&pre[i]);
printf("type in the inorder of the tree\n");
for(i=0;i scanf("%d",&in[i]);
node *root;
root=CreateTree(pre,in,n);
Print(root);

}