数据结构复习代码——递归实现二叉树的定义以及创建
1、递归实现二叉树的定义以及创建
#include<stdio.h> #include<assert.h> #include<malloc.h> #define ElemType char typedef struct BinTreeNode { ElemType data; struct BinTreeNode *leftchild; struct BinTreeNode *rightchild; }BinTreeNode; typedef struct BinTree { BinTreeNode *root; ElemType refvalue; }BinTree; void InitBinTree(BinTree *bt,ElemType ref) { bt->root = NULL; bt->refvalue = ref; } //创建二叉树 void CreateBinTree_1(BinTree *bt, BinTreeNode **t) { ElemType item; scanf("%c",&item); if(item == bt->refvalue) (*t) = NULL; else{ (*t) = (BinTreeNode*)malloc(sizeof(BinTreeNode)); assert((*t) != NULL); (*t)->data = item; CreateBinTree_1(bt,&((*t)->leftchild)); CreateBinTree_1(bt,&((*t)->rightchild)); } } void CreateBinTree_1(BinTree *bt) { CreateBinTree_1(bt,&(bt->root)); } void CreateBinTree_2(BinTree *bt, BinTreeNode *&t) { ElemType item; scanf("%c",&item); if(item == bt->refvalue) t = NULL; else{ t = (BinTreeNode*)malloc(sizeof(BinTreeNode)); assert(t != NULL); t->data = item; CreateBinTree_2(bt,t->leftchild); CreateBinTree_2(bt,t->rightchild); } } void CreateBinTree_2(BinTree *bt) { CreateBinTree_2(bt,bt->root); } int main() { BinTree mytree; InitBinTree(&mytree,'#'); CreateBinTree_2(&mytree); return 0; }