OJ14-01

读取字符串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;
}
相关推荐
tobias.b1 小时前
计算机基础知识-数据结构
java·数据结构·考研
不想看见4043 小时前
Valid Parentheses栈和队列--力扣101算法题解笔记
开发语言·数据结构·c++
计算机安禾3 小时前
【C语言程序设计】第37篇:链表数据结构(一):单向链表的实现
c语言·开发语言·数据结构·c++·算法·链表·蓝桥杯
皮卡狮4 小时前
高阶数据结构:AVL树
数据结构·算法
不要秃头的小孩5 小时前
50. 随机数排序
数据结构·python·算法
故事和你915 小时前
sdut-python-实验四-python序列结构(21-27)
大数据·开发语言·数据结构·python·算法
丶小鱼丶6 小时前
数据结构和算法之【栈】
java·数据结构
不要秃头的小孩6 小时前
力扣刷题——111.二叉树的最小深度
数据结构·python·算法·leetcode
散峰而望6 小时前
【基础算法】从入门到实战:递归型枚举与回溯剪枝,暴力搜索的初级优化指南
数据结构·c++·后端·算法·机器学习·github·剪枝
elseif1238 小时前
CSP-S提高级大纲
开发语言·数据结构·c++·笔记·算法·大纲·考纲