数据结构初阶:二叉树的链式存储结构
一、二叉树的链式结构
二叉树的链式结构主要分为二叉链和三叉链。本阶段主要讲解二叉链的结构体定义:
// 链式二叉树的节点
typedef struct BinaryTree {
Elemtype data;
struct BinaryTree* leftChild;
struct BinaryTree* rightChild;
} BTNode;
在一个二叉树的节点中,包含数据域和指针域。数据域存储当前节点的值,指针域包含其左子树和右子树的指针(地址),方便直接找到左右子树。
二、二叉树的创建
为了便于理解二叉树的基本性质和快速上手,我们手动创建一棵二叉树,暂不涉及复杂的增删查改操作。
2.1、创建二叉树节点
二叉树节点的创建与链表节点的创建类似:
// 先创建新节点
BTNode* BuyNode(Elemtype data) {
// 申请空间
BTNode* newNode = (BTNode*)malloc(sizeof(BTNode));
if (newNode == NULL) {
perror("create new node fail!\n");
}
newNode->data = data;
newNode->leftChild = newNode->rightChild = NULL;
return newNode;
}
2.2、二叉树节点的链接
通过 BuyNode 创建节点后,将根节点与左右子树进行连接:
BTNode* createNewBT() {
// 创建新节点
BTNode* NodeA = BuyNode('A');
BTNode* NodeB = BuyNode('B');
BTNode* NodeC = BuyNode('C');
BTNode* NodeD = BuyNode('D');
BTNode* NodeE = BuyNode('E');
BTNode* NodeF = BuyNode('F');
BTNode* NodeG = BuyNode('G');
BTNode* NodeH = BuyNode();
BTNode* NodeI = BuyNode();
BTNode* NodeO = BuyNode();
NodeA->leftChild = NodeB;
NodeA->rightChild = NodeC;
NodeB->leftChild = NodeD;
NodeB->rightChild = NodeE;
NodeD->leftChild = NodeH;
NodeC->leftChild = NodeF;
NodeF->leftChild = NodeI;
NodeH->leftChild = NodeO;
NodeA;
}




