[PTA] 数据结构与算法题目集 6-8 求二叉树高度 & 6-9 二叉树的遍历

6.8 二叉树高度

int GetHeight(BinTree BT)
{
    if (BT == NULL)
        return 0;

    int leftH = GetHeight(BT->Left);
    int rightH = GetHeight(BT->Right);
    if (leftH > rightH)
        return leftH + 1;
    else
        return rightH + 1;
}

6-9 二叉树的遍历

void InorderTraversal(BinTree BT)
{
    if (BT == NULL)
        return;
    InorderTraversal(BT->Left);
    printf(" %c", BT->Data);
    InorderTraversal(BT->Right);
}
void PreorderTraversal(BinTree BT)
{
    if (BT == NULL)
        return;
    printf(" %c", BT->Data);
    PreorderTraversal(BT->Left);
    PreorderTraversal(BT->Right);
}
void PostorderTraversal(BinTree BT)
{
    if (BT == NULL)
        return;
    PostorderTraversal(BT->Left);
    PostorderTraversal(BT->Right);
    printf(" %c", BT->Data);
}
void LevelorderTraversal(BinTree BT)
{
    BinTree que[1000];
    int top = -1;
    int tail = -1;
    if (BT)
        que[++tail] = BT;
    while (top < tail)
    {
        BinTree bt = que[++top];
        printf(" %c",  bt->Data);
        if (bt->Left)
            que[++tail] = bt->Left;
        if (bt->Right)
            que[++tail] = bt->Right;
    }
}
posted @ 2018-11-18 13:04  Ruohua3kou  阅读(729)  评论(0编辑  收藏  举报