数据结构实训(三)--- 二叉树的中序遍历

设计算法求二叉树的中序遍历序列。

【输入形式】一行字符串,该行是扩展二叉树的前序遍历序列,用于构造二叉树。
【输出形式】二叉树中的中序遍历序列。
【样例输入】AB#D##C##
【样例输出】
BDAC

BiTree.h 文件

#ifndef BITREE_H_INCLUDED
#define BITREE_H_INCLUDED
using namespace std;
//定义结点
template <typename DataType>
struct BiNode
{
    DataType  data;
    BiNode<DataType> *lchild,*rchild;
};

template <typename DataType>
class BiTree
{
public :
    BiTree(){root = Creat();}               // 构建函数,建立一颗二叉树
    ~BiTree(){Release(root);}               // 析构函数,释放格结点的存储空间
    void InOrder(){InOrder(root);}          // 中序遍历二叉树
private:
    BiNode<DataType> * Creat();
    void Release(BiNode<DataType> *bt);
    void InOrder(BiNode<DataType> *bt);
    BiNode<DataType> *root;

};

// 构造函数,建立一颗二叉树
template <typename DataType>
BiNode<DataType> *BiTree<DataType>::Creat()
{
    BiNode<DataType>* bt;
    char ch;
    cin>>ch;                    // 输入结点的数据信息
    if(ch == '#')bt=nullptr;    // 建立一棵空树
    else {
        bt = new BiNode<DataType>;
        bt->data = ch;
        bt->lchild = Creat();   // 递归建立左子树
        bt->rchild = Creat();   // 递归建立右子树
    }
    return bt;
}

// 析构函数,释放格结点的存储空间
template <typename DataType>
void BiTree<DataType> ::Release(BiNode<DataType> * bt)
{
    if(bt == nullptr) return;
    else {
        Release(bt ->lchild);
        Release(bt->rchild);
        delete bt;
    }
}

// 中序遍历二叉树
template <typename DataType>
void BiTree<DataType> :: InOrder(BiNode<DataType> * bt)
{
    if(bt == nullptr) return ;
    else{
        InOrder(bt->lchild);
        cout<<bt->data;
        InOrder(bt->rchild);
    }
}



#endif // BITREE_H_INCLUDED

main.cpp文件

#include<iostream>
#include"BiTree.h"
using namespace std;  // 可以不写

int main()
{
    BiTree<char> T;
    T.InOrder();
}
原文地址:https://www.cnblogs.com/DullRabbit/p/12558939.html