因此,我试图使用给定的数组创建一个二叉树,然后按顺序、预序和后序打印结果,但似乎我在某个地方犯了一个错误,但据我所知,一切都应该正常。
这是它打印出来的结果
1 2 3 4 5 6 7 8 9 10 #inorder
10 9 8 7 6 5 4 3 2 1 #postorder
1 2 3 4 5 6 7 8 9 10 #preorder
到目前为止,我就是这么做的。有人能指出这个错误,也许还能就如何修复它提出建议吗?
#include <stdio.h>
#include <stdlib.h>
typedef struct node_s node_t;
struct node_s
{
int key;
node_t *left,*right;
};
node_t *new_node(int val)
{
node_t *new;
new= malloc(sizeof (node_t));
if(new==NULL)
{
exit(1);
}
new->key=val;
new->left=NULL;
new->right=NULL;
return new;
}
void print_inorder(node_t *root)
{
node_t *new=root;
if (new != NULL) {
print_inorder(new->left);
printf("%d ",new->key);
print_inorder(new->right);
}
return;
}
void print_postorder(node_t *root)
{
node_t *new=root;
if (new != NULL) {
print_postorder(new->left);
print_postorder(new->right);
printf("%d ",new->key);
}
return;
}
void print_preorder(node_t *root)
{
node_t *new=root;
if (new != NULL) {
printf("%d ",new->key);
print_preorder(new->left);
print_preorder(new->right);
}
return;
}
node_t *insert_node(node_t *root,int val)
{
if(root==NULL)
return new_node(val);
else
{
if(val<root->left)
root->left= insert_node(root->left,val);
else if(val>root->left)
root->right= insert_node(root->right,val);
}
return root;
}
int main() {
int n;
int v[]={1,2,3,4,5,6,7,8,9,10};
node_t *root=NULL;
FILE *file;
file= fopen("file","r");
if(file==NULL)
{
exit(1);
}
for (int i = 0; i < 10; ++i) {
root= insert_node(root,v[i]);
}
print_inorder(root);
printf("
");
print_postorder(root);
printf("
");
print_preorder(root);
return 0;
}