二叉树链表结构表示法
生活随笔
收集整理的這篇文章主要介紹了
二叉树链表结构表示法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
二叉樹鏈表的結構聲明:
? struct? tree
{
???????? int data;
???????? struct tree *left;
???????? stryct tree *right;
};
??????? typedef struct tree treenode;
??????? typedef? treenode *btree;
?
二叉樹鏈表結構表示法 #include"iostream"using namespace std;
struct tree //二叉樹結構聲明
{
int data;
struct tree *left;
struct tree *right;
};
typedef struct tree treenode;
typedef treenode *btree;
/*----插入二叉樹的結點-------*/
btree insertnode(btree root,int value)
{
btree newnode; //樹根指針
btree current; //目前樹結點指針
btree back; //父結點指針
/*-----創建結點內存----*/
newnode=(btree)malloc(sizeof(treenode));
/*-------初始化-----*/
newnode->data=value;
newnode->left=NULL;
newnode->right=NULL;
if(root == NULL) //是否為根結點
{
return newnode;
}
else
{
current =root; //保留目前樹指針
while(current!=NULL)
{
back=current;
if(current->data>value)
current =current->left;
else
current=current->right;
}
if(back->data>value)
back->left=newnode;
else
back->right=newnode;
}
return root;
}
/*----創建二叉樹---*/
btree createbtree( int *data,int len)
{
btree root=NULL;
int i;
for(i=0;i<len;i++)
root=insertnode(root,data[i]);
return root;
}
/*-------兒二叉樹的輸出-------*/
void printbtree(btree root)
{
btree ptr;
ptr=root->left;
printf("輸出左子樹:\n");
while(ptr!=NULL)
{
printf("[%2d]\n",ptr->data);
ptr=ptr->left;
}
ptr=root->right;
printf("輸出右子樹:\n");
while(ptr!=NULL)
{
printf("[%2d]\n",ptr->data);
ptr=ptr->right;
}
}
/*------鏈表二叉樹---------*/
int main()
{
btree root =NULL;
int data[10]={5,6,4,8,2,3,7,1,9};
root=createbtree(data,9);
printf("樹的結點內容:\n");
printbtree(root);
}
?
轉載于:https://www.cnblogs.com/FCWORLD/archive/2010/11/21/1883472.html
總結
以上是生活随笔為你收集整理的二叉树链表结构表示法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用字符代替圆角尖角研究(转)
- 下一篇: 【留用】C#的一些好的书籍