作者nancyyen (nagey28)
看板Programming
标题[问题] C 二元树新增资料
时间Tue May 1 04:18:47 2018
我在新增二元树资料的时候新增的前两笔资料可以进去
可是到第三笔资料的时候root的内容却不见了
想问一下我是哪个地方打错Orz
struct Tree
{
int data;
struct Tree *left;
struct Tree *right;
};
typedef struct Tree *tree;
------------------------------------------------------
int main()
{
int n=0;
tree root=NULL;
while(n!=-1)
{
printf("二元树的 1)新增 2)搜寻 3)中序印出 4)後序印出 5)深度 -1)离开 :");
scanf("%d",&n);
switch(n)
{
case 1:
add(&root);
break;
-------------------------------------------------------
void add(tree *root)//新增
{
int num;
tree runptr=*root;
tree tempptr=NULL;
tree newdata=(tree)malloc(sizeof(Tree));
printf("输入数字:");
scanf("%d",&num);
if(runptr==NULL)
{
newdata->data=num;
newdata->left=NULL;
newdata->right=NULL;
*root=newdata;
}
else
{
while(runptr!=NULL)//跑完後runptr会等於NULL tempptr等於runptr的上一个节点
{
tempptr=runptr;
if(num>runptr->data)//右移
runptr=runptr->right;
else if(num<runptr->data)//左移
runptr=runptr->left;
}
if(num>tempptr->data)//放右边
{
tempptr->right=newdata;
newdata->data=num;
newdata->left=NULL;
newdata->right=NULL;
}
else if(num<tempptr->data)//放左边
{
tempptr->left=newdata;
newdata->data=num;
newdata->left=NULL;
newdata->right=NULL;
}
}
free(runptr);
free(tempptr);
}
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 101.13.23.248
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Programming/M.1525119529.A.59E.html
1F:→ outofyou: free时机140.130.198.136 05/01 12:53
2F:推 cutekid: 一开始的 root 没有实体! 111.246.60.192 05/01 14:46
3F:推 b0920075: add里面应该不用free吧,会有uaf问题 223.139.223.58 05/10 03:37