我很困惑,我在做什麼錯誤。爲什麼不按預訂,後序和中序打印樹。我在我困惑的代碼行旁寫下了我的問題。另外我不明白如何與結構相關。C中的二叉搜索樹。
#include <stdio.h>
#include<stdlib.h>
typedef struct BST_{
int data;
struct BST_ *lchild, *rchild, *parent;
}BST;
typedef struct BiTree_{
int size;
BST *root; // is it possible to relate this root with the pointer parent of type BST? i yes then how?
}BiTree;;
BST *temp;
BST *createNode(int data){
BST *new_ele;
new_ele=(BST*)malloc(sizeof(BST));
new_ele->data=data;
new_ele->lchild=NULL;
new_ele->rchild=NULL;
new_ele->parent=NULL;
return new_ele;
}
void insertNode(BST *temp,BST *r,int data){
if(temp==NULL){
temp=createNode(data);
}
else if(temp->data >= r->data){
if(r->rchild==NULL){
r->rchild=temp;
}
else{
insertNode(r->rchild,temp,data);
}
}
else if(temp->data <= r->data){
if(r->lchild==NULL){
r->lchild=temp;
}
else{
insertNode(r->lchild,temp,data);
}
}
// return r->data; //why cann't i do this?
}
void preorder(BST *r){
if(r!=NULL){
printf("%d",r->data);
preorder(r->lchild);
preorder(r->rchild);
}
}
void inorder(BST *c){
if(c!=NULL){
inorder(c->lchild);
printf("%d",c->data);
inorder(c->rchild);
}
}
void postorder(BST *r){
if(r!=NULL){
postorder(r->lchild);
postorder(r->rchild);
printf("%d",r->data);
}
}
void delet(BST *r){
if(r!=NULL){
free(r);
}
}
void main(){
BST *new_node,*r=NULL;
BiTree *search;
search=malloc(sizeof(BiTree));
search->root=NULL;
search->size=0;
int i,a,n,data;
printf("Enter the number of element to be inserted\n");
scanf("%d",&n);
printf("Enter the data\n");
for(i=0;i<n;i++){
scanf("%d",&data);
insertNode(temp,r,data);
// printf("Enter the data %d\n",r->data); // unable to print this
search->size++;
}
printf("size is %d\n",search->size);
preorder(r);// why cann't i print the data of r. r is the root of the tree.
postorder(r);
inorder(r);
delet(r);
}
請通過提供輸入,預期輸出和實際輸出來更準確地描述程序的行爲。 – kaylum
'r'永遠不是NULL。 – hobbs
它只是要求輸入並給出大小。在那裏我想打印預先訂購的樹,後序和中序,然後刪除它。我不知道如何解決它。 –