zoukankan      html  css  js  c++  java
  • 二叉树层次遍历(以先序输入)

    按层次遍历的原则是先被访问的结点的左右儿子结点也先被访问,因此需引入先进先出的队列作为辅助工具。

    算法思想为:

    1)将二叉树根入队列;

    2)循环直到队列为空

       2.1)将队头元素出队列,

       2.2)访问结点数据域,

       2.3)判断此元素是否有左右孩子,若有,则将它的左右孩子依次入队,否则转(2);

    #include <iostream>
    #include <cstdio>
    #include <malloc.h>
    using namespace std;
    #define MAXSIZE 100
    typedef char DataType;
    typedef struct BiTnode
    {
        DataType data;
        struct BiTnode *lchild,*rchild;
    }BiTNode,*BiTree;
    typedef struct SQueue
    {
        BiTree data[MAXSIZE];
        int front,rear;
    }SQueue,*Queue;
    BiTree creatTree(BiTree root)
    {
        DataType ch;
        root=(BiTree)malloc(sizeof(BiTNode));
        scanf("%c",&ch);
        if(ch=='#') return 0;
        root->data=ch;
        root->lchild=creatTree(root->lchild);
        root->rchild=creatTree(root->rchild);
        return root;
    }
    void InitQueue(Queue Q)
    {
        Q->front=Q->rear=0;
    }
    int IsEmptyQueue(Queue Q)
    {
        return Q->rear==Q->front?1:0;
    }
    void EnQueue(BiTree root,Queue Q)
    {
        if((Q->rear+1)%MAXSIZE==Q->front)
        {
            printf("Queue is fulled!
    ");
            return  ;
        }
        Q->rear=(Q->rear+1)%MAXSIZE;
        Q->data[Q->rear]=root;
    }
    BiTree Gethead(Queue Q)
    {
        if(IsEmptyQueue(Q)) return 0;
        BiTree root;
        root=Q->data[(Q->front+1)%MAXSIZE];
        Q->front=(Q->front+1)%MAXSIZE;
        return root;
    }
    void LevelOrder(BiTree root)
    {
        SQueue Q;
        BiTree t;
        if(!root) return ;
        InitQueue(&Q);
        EnQueue(root,&Q);
        while(!IsEmptyQueue(&Q))
        {
            t=Gethead(&Q);
            printf("%c ",t->data);
            if(t->lchild!=NULL) EnQueue(t->lchild,&Q);
            if(t->rchild!=NULL) EnQueue(t->rchild,&Q);
        }
    }
    int main()
    {
        BiTree tree;
        tree=creatTree(tree);
        LevelOrder(tree);
        return 0;
    }
  • 相关阅读:
    2019高考数学理科Ⅱ卷解析版[解答题]
    对风说爱你
    佛教人生-伴侣
    【Echarts每天一例】-1
    算法中涉及的专业英语
    python--随机函数(random,uniform,randint,randrange,shuffle,sample)
    【linux shell系列--1】crontab命令
    【Python爬虫实战--3】html写正则表达式
    mysql启动参数 skip-grant-tables
    php通过反射执行某方法
  • 原文地址:https://www.cnblogs.com/shinianhuanniyijuhaojiubujian/p/8928045.html
Copyright © 2011-2022 走看看