二叉树的构建及各种遍历

#include<iostream>
#include<cstdio>
#include<stdlib.h>
#include<algorithm>
using namespace std;


//构建二叉树及其中的各种运算


#define Telemtype char


const int maxsize = 100;
typedef struct
{
    //二叉树的顺序储存
    Telemtype *data;
    int nod;
}Sqbitree;


typedef struct Bitnode
{
    //二叉树的链表储存
    Telemtype data;
    struct Bitnode *l, *r;
}Bitnode, *Bitree;


void creattree(Bitree &T)
{
    //先序遍历二叉树过程中输入结点,建立二叉树链表储存结构,指针T指向根结点
    char ch;
    cin>>ch;
    if(ch == '#')
        T= NULL;
    else
    {
        T = new Bitnode;
        T->data = ch;
        creattree(T->l);
        creattree(T->r);
    }
}


void Bitreedepth1(Bitree T, int h, int &depth)
{
    //求二叉树有多少层,输出depth
    if(T)
    {
        if(h > depth)
            depth = h;
        Bitreedepth1(T->l, h+1, depth);
        Bitreedepth1(T->r, h+1, depth);
    }
}


int Bitreedepth2(Bitree T)
{
    //后序遍历,输出层数
    if(!T)
        return 0;
    else
    {
        int hL = Bitreedepth2(T->l);
        int hR = Bitreedepth2(T->r);
        if(hL >= hR)
            return hL+1;
        else return hR+1;
    }
}


void preorder(Bitree &T)
{
    //先序遍历并输出
    if(T)
    {
       cout<<T->data;
       preorder(T->l);
       preorder(T->r);
    }
}


void inorder(Bitree &T)
{
    //中序遍历并输出
  if(T)
  {
     inorder(T->l);
     cout<<T->data;
     inorder(T->r);
  }
}


void lastorder(Bitree &T)
{
    //后序遍历并输出
  if(T)
  {
     lastorder(T->l);
     lastorder(T->r);
     cout<<T->data;
  }
}


int main()
{
    Bitnode *T;
    creattree(T);


    preorder(T);
    cout<<endl;


    inorder(T);
    cout<<endl;


    lastorder(T);
    cout<<endl;


    cout<<Bitreedepth2(T)<<endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值