码迷,mamicode.com
首页 > 其他好文 > 详细

建立二叉树(二叉链表存储)

时间:2020-04-14 18:25:12      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:info   inf   typedef   malloc   img   存储   lib   结束   tree   

技术图片

 

#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\n", myBT->data);
	printf("树的叶子节点是:%d,%d\n", 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\n", myBT->data);
	printf("树的根结点的左结点是:%d\n", myBT->LChild->data);
	printf("树的根结点的右结点是:%d\n", myBT->RChild->data);
}

技术图片

 

建立二叉树(二叉链表存储)

标签:info   inf   typedef   malloc   img   存储   lib   结束   tree   

原文地址:https://www.cnblogs.com/shanlu0000/p/12699672.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!