第四章-二叉树的代码 、二叉树前序中序后序遍历、及运用

哔哩哔哩数据结构讲解地址:https://space.bilibili.com/356198029

本代码视频讲解地址:https://www.bilibili.com/video/av68531757

//二叉树的操作集合
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
    char data;
    struct Node* lchild;
    struct Node* rchild;
} BTNode;
/**
 * 二叉树的建立
 */
void BuildBT(BTNode** tree)
{
    char ch;
    scanf("%c",&ch);//输入数据
    if(ch == '#') //如果这个节点的数据是# 则说明这个节点为空
        *tree = NULL;
    else {
        *tree = (BTNode*)malloc(sizeof(BTNode));//申请一个节点的内存
        (*tree)->data = ch;//数据写入到节点里面
        BuildBT(&(*tree)->lchild);//递归建立左子树
        BuildBT(&(*tree)->rchild);//递归建立右子树
    }
}
/**
 * 二叉树的销毁
 */
void DestroyBT(BTNode* tree)//传入根结点
{
    if(tree != NULL)
    {
        DestroyBT(tree->lchild);
        DestroyBT(tree->rchild);
        free(tree);//释放内存空间
    }
}
/**
 *二叉树的前序遍历
 */
void Preorder(BTNode* node)
{
    if(node == NULL)
        return;
    else
    {
        printf("%c",node->data);
        Preorder(node->lchild);
        Preorder(node->rchild);
    }
}
/**
 * 二叉树的中序遍历
 * inorder traversal
 */
void Inorder(BTNode* node)
{
    if(node == NULL)
        return;
    else
    {
        Inorder(node->lchild);
        printf("%c",node->data);
        Inorder(node->rchild);
    }
}
/**
 * 后序遍历
 */
void Postorder(BTNode* node)
{
    if(node == NULL)
        return;
    else
    {
        Postorder(node->lchild);
        Postorder(node->rchild);
        printf("%c",node->data);
    }
}
/**
 * 获取树的高度
 */
int GetHeight(BTNode* node) {
    int Height = 0;
    if (node == NULL)
        return 0;
        //树的高度 = max(左子树的高度,右子树的高度) + 1
    else {
        int L_Height = GetHeight(node->lchild);
        int R_Height = GetHeight(node->rchild);
        Height = L_Height >= R_Height ? L_Height + 1 : R_Height + 1;
    }
    return Height;
}

int main() {
    BTNode* BTree;//定义一个二叉树(指向根节点的指针)
    printf("请输入一颗二叉树先序序列以#表示空节点");
    BuildBT(&BTree);
    printf("先序序列:");
    Preorder(BTree);
    printf("\n中序序列:");
    Inorder(BTree);
    printf("\n后序序列:");
    Postorder(BTree);
    printf("树的高度为:%d",GetHeight(BTree));
    return 0;
}
// ABC##DE##F##G##

 

posted @ 2019-11-15 16:32  小尾学长  阅读(240)  评论(0编辑  收藏  举报