二叉树的建立
时间:2014-04-02 03:42 来源: 我爱IT技术网 作者:微风
上一篇我和大家分享了关于《二叉树的遍历》,那接下来我继续和大家分享关于二叉树的相关知识。下面的C++代码主要是撰写二叉树的建立。程序所实现的思路首先是先创建n个元素,struct node *create(int n),只需要在构造函数中定义整形的n,即int n,最后借助指针来进行遍历,并显示相应的二叉树。创建二叉树的关键步骤在于递归函数的使用。即t=create(2); //也用递归 创建。下面是详细的源代码,分享给大家。
#include
#include
#include
typedef struct node{
int num;
struct node *next;
};
struct node *create(int n) //创建n个元素
{
int x, i;
struct node *head, *p, *r;
head=(struct node*)malloc(sizeof(struct node));
r=head;
printf("请输入数字\r\n");
for(i=0; i
{
scanf("%d", &x);
p=(struct node*)malloc(sizeof(struct node));
p->num=x;
r->next=p;
r=p;
}
r->next=NULL;
return(head);
}
//Node *Create(int n){ //Node * =node 因为node就是指针
//
// node head ,p,r;
// int a;
// head= (Node *)malloc(sizeof (Node));
// r=head;
// for(int i=0;i
// {
// scanf("%d",&a);
//
// p = (Node *)malloc(sizeof (Node));
// p->data=a;
// r->next=p;
// r=p;
// }
// r->next=NULL;
// return head;
//}
//
//
void displayList(struct node *head)//显示二叉树
{ struct node *pt;
pt=NULL;
pt->next=head;
while(pt!=NULL)
{
printf("%d\n",pt->num);
pt=pt->next;
}
}
void main(){
struct node *t;
t=NULL;
int a=2;
t=create(2); //也用递归 创建
displayList(t);
}
本文来源 我爱IT技术网 http://www.52ij.com/jishu/4705.html 转载请保留链接。
- 评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
-
