OJ14-01

该篇文章介绍了如何使用C语言构建一个二叉树,通过输入字符串abcdefghij层次建树,并实现了前序遍历,输出结果为abdhiejcfg。
摘要由CSDN通过智能技术生成

读取字符串abcdefghij,然后层次建树建立一颗二叉树,然后前序遍历输出abdhiejcfg,注意不要打印前序遍历几个汉字

#include <stdio.h>
#include <stdlib.h>

typedef char BiElemType;
typedef struct BiTNode {
    BiElemType data;
    struct BiTNode *lChild;
    struct BiTNode *rChild;//左右节点
} BiTNode, *BiTree;
//辅助队列
typedef struct tag {
    BiTree p;//树的某一个节点,指针类型,保存申请节点的指针
    struct tag *pnext;
} tag_t, *ptag_t;

//前序遍历,深度优先遍历
void preOrder(BiTree p) {
    if (p) {
        printf("%c",p->data);
        preOrder(p->lChild);
        //递归
        preOrder(p->rChild);
    }
}

void inOrder(BiTree p) {
    if (p) {
        inOrder(p->lChild);
        printf("%c", p->data);
        //递归
        inOrder(p->rChild);
    }
}

void postOrder(BiTree p) {
    if (p) {
        postOrder(p->lChild);
        postOrder(p->rChild);
        printf("%c", p->data);
        //递归
    }
}

int main() {
    BiTree p;//指向新申请的树节点
    BiTree tree = NULL;//初始化根节点
    //队头,队尾,新节点,新节点父元素
    ptag_t phead = NULL, ptail = NULL, listpnew = NULL, pucr = NULL;
    char c;
    while (scanf("%c", &c)) {
        if (c == '\n') {
            break;;
        }
        p = (BiTree) calloc(1, sizeof(BiTNode));
        p->data = c;
        listpnew = (ptag_t) calloc(1, sizeof(tag_t));//给队列节点申请空间
        listpnew->p = p;
        if (tree == NULL) {
            tree = p;
            //第一个节点既是队列头也是队列尾
            phead = listpnew;
            ptail = listpnew;
            pucr = listpnew;
        } else {
            ptail->pnext = listpnew;
            ptail = listpnew;
            //将数放入左孩子
            if (pucr->p->lChild == NULL) {
                pucr->p->lChild = p;
            } else if (pucr->p->rChild == NULL) {
                pucr->p->rChild = p;
                pucr = pucr->pnext;
            }
        }
    }
    preOrder(tree);
//    inOrder(tree);
//    postOrder(tree);
    return 0;
}

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值