建立一棵二元樹-C語言

2020-08-09 09:51:21

建立一棵如圖所示二元樹:節點數據爲圓圈內數據,節點關係如圖所示

標題

#include <stdio.h>
#include <stdlib.h>//用於使用malloc()函數
#define TElemType int

typedef struct BiTNode{
    TElemType data;
    struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;

void CreateBiTree(BiTree *T){

    //爲節點分配空間,有的指向NULL
    (*T)=(BiTNode*)malloc(sizeof(BiTNode));//4
    (*T)->lchild=(BiTNode*)malloc(sizeof(BiTNode));//3
    (*T)->rchild=NULL;//
    (*T)->lchild->lchild=(BiTNode*)malloc(sizeof(BiTNode));//100
    (*T)->lchild->rchild=(BiTNode*)malloc(sizeof(BiTNode));//25
    (*T)->lchild->lchild->lchild=NULL;//
    (*T)->lchild->lchild->rchild=NULL;//
    (*T)->lchild->rchild->lchild=(BiTNode*)malloc(sizeof(BiTNode));//7
    (*T)->lchild->rchild->rchild=(BiTNode*)malloc(sizeof(BiTNode));//4
    (*T)->lchild->rchild->lchild->lchild=NULL;//
    (*T)->lchild->rchild->lchild->rchild=NULL;//
    (*T)->lchild->rchild->rchild->lchild=NULL;//
    (*T)->lchild->rchild->rchild->rchild=NULL;//

   //填寫節點數據

    (*T)->data=4;
    (*T)->lchild->data=3;
    (*T)->lchild->lchild->data=100;
    (*T)->lchild->rchild->data=25;
    (*T)->lchild->rchild->lchild->data=7;
    (*T)->lchild->rchild->rchild->data=4;

}

int main() {
    BiTree Tree;
    CreateBiTree(&Tree);
    printf("%d",Tree->lchild->rchild->lchild->data);//列印節點數據爲7的節點數據,也就是7
    return 0;
}