二叉树,Do you love me ?

来源:互联网 发布:方大同 西游记淘宝 编辑:程序博客网 时间:2024/06/06 07:05

如果有来生,
要做一棵树,
站成永恒,
没有悲欢的姿势。

一半在尘土里安详,
一半在风里飞扬,
一半洒落阴凉,
一半沐浴阳光。

 

                                  --三毛《说给自己听》


-------------------------------------------------------------------------------------------------------------------------------------------


今儿咱说一棵树,这棵树不是别的,就是大名鼎鼎( chòu míng zhāo zhù )的二叉树。



你见过如此蔫不拉几的树吗?


//二叉树:你若是不喜欢我,为何还要留着我不放?//她:对不起。

二叉树其实长这样:它是由一个根结点和两个子二叉树(左子树、右子树)组成的。



我想拥有一棵属于我的二叉树,可以吗?

比如,比如,比如它


那先来个结构的定义吧

typedef struct TREE{int data;//数据元素 struct TREE *left;//左子树struct TREE *right;//右子树}Tree;

似乎还缺点什么?

嗯,左子树!右子树!

//生成左子树Tree * createLeft(Tree *curr,int value){Tree *temp,*insert;//两个指针 temp=curr->left;//把左子树的指针暂存在temp指针上 insert=(Tree *)malloc(sizeof(Tree));//给要插入的子树分配空间insert->data=value;//赋值insert->left=temp;insert->right=NULL;curr->left=insert;return curr->left;//返回生成的左子树 }

大功告成!


我有此树,今生足以。


------------------------------------------------------------------------------------------------------------------------------------------------


下面是完整的程序及运行结果

main.c:#include <stdio.h>#include <stdlib.h>#include "treelib.h" int main() {Tree *root,*point;initiate(&root);point=createLeft(root,1);point=createLeft(point,2);point=createRight(point,3);point=createRight(root->left,4);traversals(root);return 0;}

treelib.h:typedef struct TREE{int data;//数据元素 struct TREE *left;//左子树struct TREE *right;//右子树}Tree;//初始化:根节点 void initiate(Tree **root){*root=(Tree *)malloc(sizeof(Tree));//分配内存空间 (*root)->data=0;//默认根节点为0 (*root)->left=NULL; (*root)->right=NULL;} //生成左子树Tree * createLeft(Tree *curr,int value){Tree *temp,*insert;//两个指针 temp=curr->left;//把左子树的指针暂存在temp指针上 insert=(Tree *)malloc(sizeof(Tree));//给要插入的子树分配空间insert->data=value;//赋值insert->left=temp;insert->right=NULL;curr->left=insert;return curr->left;//返回生成的左子树 }//生成右子树:与生成左子树差不多 Tree * createRight(Tree *curr,int value){Tree *temp,*insert;temp=curr->right;//把右子树的指针暂存在temp指针上 insert=(Tree *)malloc(sizeof(Tree));//给要插入的子树分配空间insert->data=value;//赋值insert->right=temp;insert->left=NULL;curr->right=insert;return curr->right;//返回生成的右子树 }//遍历树:前序遍历 void traversals(Tree *curr){if(curr!=NULL){printf("%4d",curr->data);//打印 traversals(curr->left);//递归 traversals(curr->right);}}

运行结果:







0 0
原创粉丝点击