#include<stdio.h> #include<stdlib.h> //二叉链表 //typedef struct BitLink { // int data; // struct BitLink* leftChild; //左指针 // struct BitLink* rightChild; //右指针 //}bitlink; //用二叉链表存储方式建树 typedef struct BitTree { int data; struct BitTree* LChild; //左子树 struct BitTree* RChild; //右子树 }bittree; bittree* createBitTree(bittree* BT) { BT = (bittree*)malloc(sizeof(bittree)); BT->data = 1; BT->LChild = (bittree*)malloc(sizeof(bittree)); BT->RChild = (bittree*)malloc(sizeof(bittree)); BT->LChild->data = 2; BT->LChild->RChild = NULL; BT->RChild->data = 3; BT->RChild->LChild = NULL; BT->RChild->RChild = NULL; BT->LChild->LChild = (bittree*)malloc(sizeof(bittree)); BT->LChild->LChild->data = 4; BT->LChild->LChild->LChild= NULL; BT->LChild->LChild->RChild = NULL; return BT; } void main() { bittree* myBT = NULL; myBT = createBitTree(myBT); printf("树的根节点是:%d ", myBT->data); printf("树的叶子节点是:%d,%d ", myBT->LChild->LChild->data, myBT->RChild->data); }
使用递归的方式建立:
#include<stdio.h> #include<stdlib.h> //用二叉链表存储方式建树(完全二叉树) typedef struct BitTree { int data; struct BitTree* LChild; //左子树 struct BitTree* RChild; //右子树 }bittree; //创建二叉树 bittree* createBitTree(bittree* BT) { int num = 0; scanf("%d", &num); if (num != -1) { //输入-1代表结束 BT = (bittree*)malloc(sizeof(bittree)); BT->data = num; printf("输入%d的左结点值:", BT->data); BT->LChild=createBitTree(BT->LChild); printf("输入%d的右结点值:", BT->data); BT->RChild=createBitTree(BT->RChild); return BT; } } void main() { bittree* myBT = NULL; myBT=createBitTree(myBT); printf("树的根结点是:%d ", myBT->data); printf("树的根结点的左结点是:%d ", myBT->LChild->data); printf("树的根结点的右结点是:%d ", myBT->RChild->data); }