私は何をしているのか混乱しています。何故なら、それはあらかじめ注文された、注文された、注文された順で木を印刷しないのです。私は混乱しているコードの行の横に私の質問を書いています。プラス私は構造体に関連する方法を理解していない。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
それは入力を求めてサイズを与えるだけです。ここでは、ツリーをプリオーダー、ポストオーダー、インオーダーで印刷してから削除したいと考えています。私はそれを修正する方法を知らない。 –