2020-9-27 //严蔚敏《数据结构》 //二叉链表: 递归、非递归(非递归用栈)先序、中序、后序遍历(非递归后序遍历麻烦点,需要用到flag标志)

本文详细介绍了如何使用递归和非递归(借助栈)方法实现二叉链表的先序、中序和后序遍历。在非递归后序遍历中,由于其复杂性,需要设置flag标志来辅助完成遍历。测试代码已上传至链接:https://blog.csdn.net/weixin_45888287/article/details/109727927。
摘要由CSDN通过智能技术生成

精简代码见新的链接:
https://blog.csdn.net/weixin_45888287/article/details/109727927

//严蔚敏《数据结构》
//二叉链表: 递归、非递归(非递归用栈)先序、中序、后序遍历(非递归后序遍历麻烦点,需要用到flag标志)
//以及层序遍历(层序用队列)
//自学中,加油!!!
//过程很痛,但结果很美
#include<iostream>
using namespace std;
#define TElemType double

typedef struct BiTNode
{
    TElemType data;
    struct BiTNode* lchild,* rchild;
    int flag;//标志变量 标志非递归的后序遍历
}BiTNode,* BiTree;

bool Creat_BiTree(BiTree& T)//递归先序创建并输入
{
    TElemType num;
    if(cin>>num){//此处应用if而不是while循环  这是在用递归,就不用while循环了
        T=new BiTNode;
        if(!T)
            return false;
        T->data=num;
        Creat_BiTree(T->lchild);
        Creat_BiTree(T->rchild);
    }
    if(!cin)
        T=nullptr;
    if(!cin){
        cin.clear();
        while(cin.get()!='\n')
            continue;
    }
    return true;
}

void PreOrder_Bitree(BiTree T)//递归先序遍历
{
    if(T){
        cout<<T->data<<endl;
        PreOrder_Bitree(T->lchild);
        PreOrder_Bitree(T->rchild);
    }
}

void InOrder_bitree(BiTree T)//递归中序遍历
{
    if(T){
        InOrder_bitree(T->lchild);
        cout<<T->data<<endl;
        InOrder_bitree(T->rchild);
    }
}

void PostOrder_BiTree(BiTree T)//递归后序遍历
{
    if(T){
        PostOrder_BiTree(T->lchild);
        PostOrder_BiTree(T->rchild);
        cout<<T->data<<endl;
    }
}
//构造的
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值