69,371
社区成员
发帖
与我相关
我的任务
分享
typedef int keytype;
typedef struct BinTree{
keytype key;
struct BinTree *lchild,*rchild;
} *BSTree,BSTNod ;
void InsertBST(BSTree &bst,int key)
{
BSTNod *s;
if ( bst == NULL)/*递归结束条件*/
{
s = (BSTree)malloc(sizeof(BSTNod)) ;//申请新的节点s
s->key = key;
s->lchild =NULL;
s->rchild =NULL;
bst = s ;
}
else if (key < bst->key )
{
InsertBST(bst->lchild,key);/*将s插入左子树*/
}
else if (key > bst->key)
{
InsertBST(bst->rchild,key);/*将s插入右子树*/
}
}
void CreateBST(BSTree& bst)
{
int key;
bst = NULL;
scanf("%d",&key);
while (key != 0) /*输入0结束*/
{
InsertBST(bst,key);
scanf("%d",&key);
}
}
void InOrder(BSTree bst)
{
if (bst != NULL)
{
InOrder(bst->lchild);
printf("%d ",bst->key);
InOrder(bst->rchild);
}
}
//添加一个释放所有节点的代码
void Release(BSTree & root){
if(root){
Release (root->lchild);
Release (root->rchild);
free(root);
}
}
int main()
{
BSTree root = NULL; ///直接定义为节点(指针)类型即可
CreateBST(root);
InOrder(root);
Release(root)
return 0;
}
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int key;
struct node *lchild,*rchild;
}BSTNod,*BSTree;
void InsertBST(BSTree *bst,int key)
{
BSTNod *s;
if ( *bst == NULL)/*递归结束条件*/
{
s = (BSTree)malloc(sizeof(BSTNod)) ;//申请新的节点s
s->key = key;
s->lchild =NULL;
s->rchild =NULL;
*bst = s ; //这地方修改一下,不应该给 bst 赋 地址值
//1)局部变量地址不能储存,
//2)bst 是节点(指针)的地址,我们要改变的是节点(指针)的值
}
else if (key < ( (*bst)->key) )
{
InsertBST(&((*bst)->lchild),key);/*将s插入左子树*/
}
else if (key > ((*bst)->key))
{
InsertBST(&((*bst)->rchild),key);/*将s插入右子树*/
}
}
void CreateBST(BSTree *bst)
{
int key;
///bst = NULL; ///不可给节点(指针)的地址赋值
*bst = NULL; /// 应该给节点(指针)赋值,
scanf("%d",&key);
while (key != 0) /*输入0结束*/
{
InsertBST(bst,key);
scanf("%d",&key);
}
}
void InOrder(BSTree bst) ///遍历不修改节点本身,直接传递跟指针就可以了。
{
if (bst != NULL)
{
InOrder(bst->lchild); //直接传递指针
printf("%d ",bst->key); //直接指向
InOrder(bst->rchild); //直接传递指针
}
}
int main()
{
BSTree root = NULL;
CreateBST(&root);
InOrder(root);
return 0;
}
如此修改一下,就好了
其实如果是C++可以传递引用
这样就不必传递节点的指针了
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int key;
struct node *lchild,*rchild;
}BSTNod,*BSTree;
void InsertBST(BSTree *bst,int key)
{
BSTNod *s;
if ( bst == NULL)/*递归结束条件*/
{
s = (BSTree)malloc(sizeof(BSTNod)) ;//申请新的节点s
s->key = key;
s->lchild =NULL;
s->rchild =NULL;
bst = &s ;
}
else if (key < ( (*bst)->key) )
{
InsertBST(&((*bst)->lchild),key);/*将s插入左子树*/
}
else if (key > ((*bst)->key))
{
InsertBST(&((*bst)->rchild),key);/*将s插入右子树*/
}
}
void CreateBST(BSTree *bst)
{
int key;
bst = NULL;
scanf("%d",&key);
while (key != 0) /*输入0结束*/
{
InsertBST(bst,key);
scanf("%d",&key);
}
}
void InOrder(BSTree *bst)
{
if (bst != NULL)
{
InOrder(&(*bst)->lchild);
printf("%d ",(*bst)->key);
InOrder(&(*bst)->rchild);
}
}
int main()
{
BSTree *root = NULL;
CreateBST(root);
InOrder(root);
return 0;
}