自己編的c語言建立二叉樹的代碼,運行時出錯了,自己找不到錯誤,求大神幫忙,指點,急.
#include
#include
typedef struct tnode Tnode;
struct tnode
{
Tnode *left;
Tnode *right;
int data;
};
Tnode *new_tnode(int data)
{
Tnode *new = malloc(sizeof(Tnode));
new->left=NULL;
new->right=NULL;
new->data=data;
return new;
}
void insert(Tnode *root,Tnode *tree)
{
if(root==NULL)
{
tree=root;
return;
}
if(root->datadata)
{
tree->left=root;
insert(root,tree->left);
}
else if(root->data>tree->data)
{
tree->right=root;
insert(root,tree->right);
}
}
void printout(Tnode *tree)
{
if(tree==NULL)
{
return;
}
printf("%d",tree->data);
printout(tree->left);
printout(tree->right);
}
int main()
{
Tnode *tree=NULL;
int i;
int data;
for(i=0;i<10;i++)
{
scanf("%d",&data);
insert(new_tnode(data),tree);
}
printout(tree);
return 0;
}
#include<stdio.h>
typedef struct tnode Tnode;
struct tnode
{
Tnode *left;
Tnode *right;
int data;
};
Tnode *new_tnode(int data)
{
//不能用new定義變量,是保留字
Tnode *node = (Tnode* )malloc(sizeof(Tnode));
node->left=NULL;
node->right=NULL;
node->data=data;
return node;
}
void insert(Tnode *root,Tnode *node)
{
if(root == NULL)
{
root = node;
return;
}
if(node->data < root->data )
{
if(root->left == NULL){
root->left = node;
}else{
insert(root->left,node);
}
}
else if(node->data > root->data )
{
if(root->right == NULL){
root->right = node;
}else{
insert(root->right,node);
}
}
}
void printout(Tnode *tree)
{
if(tree == NULL)
{
return;
}
printf("%d",tree->data);
printout(tree->left);
printout(tree->right);
}
int main()
{
Tnode *tree = NULL;
int i;
int data;
for(i=0; i<10; i++)
{
printf("請輸入數據%d:",(i+1));
scanf("%d",&data);
//這裡加上&符號,否則的話tree一直是null導致輸出孔
insert(&tree,new_tnode(data));
}
printf("輸出數據:\n");
printout(tree);
return 0;
}