今天又再学树,我是跟着视频里的老师一步步敲出了代码,但是目前还无法吃透
(;′д`)ゞ花了我两个小时。。
明天继续,先附上我的代码(跟着视频莫名其妙的敲出来了,我还没看懂):
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
typedef struct Data
{
int first;
char second[20];
}data,*lpdata;
typedef struct Treenode
{
data sum;
struct Treenode *L;
struct Treenode *R;
}node,*lpnode;
typedef struct Searchtree
{
node* root;
int treesize;
}tree,*lptree;
lpnode newnode(data sum)
{
lpnode news=(lpnode)malloc(sizeof(node));
news->sum=sum;
news->L=NULL;
news->R=NULL;
return news;
}
lptree ctree()
{
lptree t=(lptree)malloc(sizeof(tree));
t->root=NULL;
t->treesize=0;
return t;
}
int size(lptree t)
{
return t->treesize;
}
int empty(lptree t)
{
if(t->treesize==0)
return 1;
else
return 0;
}
void innode(lptree t,data sum)
{
lpnode pmove=t->root;;
lpnode pmove1=NULL;
while(pmove!=NULL)
{
//记录当前位置去移动
pmove1=pmove;
//移动:根据关键字去移动
if(sum.first<pmove->sum.first)
{
pmove=pmove->L;
}
else if(sum.first>pmove->sum.first)
{
pmove=pmove->R;
}
else//相同,采用保留最后一次的插入元素
{
strcpy(pmove->sum.second,sum.second);
return;
}
}
lpnode news=newnode(sum);
if(t->root==NULL)
{
t->root=news;
}
else
{
if(pmove1->sum.first>sum.first)
{
pmove1->L=news;
}
else
{
pmove1->R=news;
}
}
}
void mid(lpnode p)
{
if(p!=NULL)
{
mid(p->L);
printf("%d %s\n",p->sum.first,p->sum.second);
mid(p->R);
}
}
void printtree(lptree t)
{
mid(t->root);
}
int main()
{
data a[4]={100,"a",50,"b",70,"c",120,"d"};
lptree t=ctree();
for(int i=0;i<4;i++)
{f
innode(t,a[i]);
}
printtree(t);
return 0;
}
明天一定要弄懂二叉树,加油{{{(>_<)}}}
|