二叉树遍历递归实现(前中后与层序遍历)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40475529/article/details/80316886
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
const int MA=100;
template<class T>
struct ThrBiNode
{
    T data;
    BiNode<T> *lchild;
    BiNode<T> *rchild;
};
template<class T>
class BiTree
{
public:
    BiTree(){root=creat(root);}
    ~BiTree(){release(root);}
    void preorder(){preorder(root);}
    void inorder(){inorder(root);}
    void postorder(){postorder(root);}
    void levelorder();
private:
    BiNode<T> *root;
    void preorder(BiNode<T> *bt);
    void inorder(BiNode<T> *bt);
    void postorder(BiNode<T> *bt);
    BiNode<T> *creat(BiNode<T> *bt);
    void release(BiNode<T> *bt);
};
template<class T>
BiNode<T>* BiTree<T>::creat(BiNode<T>* bt)
{
    T ch;
    cin>>ch;
    if(ch=='#')  bt=NULL;
    else
    {
        bt=new BiNode<T>;
        bt->data=ch;
        bt->lchild=creat(bt->lchild);
        bt->rchild=creat(bt->rchild);
    }
    return bt;
}
template<class T>
void BiTree<T>::release(BiNode<T> *bt)
{
    if(bt!=NULL)
    {
        release(bt->lchild);
        release(bt->rchild);
        delete bt;
    }
}
template<class T>
void BiTree<T>::preorder(BiNode<T> *bt)
{
    if(bt==NULL) return;
    else
    {
        cout<<bt->data;
        preorder(bt->lchild);
        preorder(bt->rchild);
    }
}
template<class T>
void BiTree<T>::inorder(BiNode<T> *bt)
{
    if(bt==NULL) return;
    else
    {
        inorder(bt->lchild);
        cout<<bt->data;
        inorder(bt->rchild);
    }
}
template<class T>
void BiTree<T>::postorder(BiNode<T> *bt)
{
    if(bt==NULL) return;
    else
    {
        postorder(bt->lchild);
        postorder(bt->rchild);
        cout<<bt->data;
    }
}
template<class T>
void BiTree<T>::levelorder()
{
    int front=0,rear=00;
    BiNode<T> *Q[MA];
    if(root==NULL) return;
    Q[rear++]=root;
    while(front!=rear)
    {
        BiNode<T> *q=Q[front++];
        cout<<q->data;
        if(q->lchild!=NULL) Q[rear++]=q->lchild;
        if(q->rchild!=NULL) Q[rear++]=q->rchild;
    }
}

int main()
{
    //freopen("D:\\input.txt","r",stdin);
    BiTree<char> tree;
    cout<<" 前序遍历: ";
    tree.preorder();
    cout<<endl;
    cout<<" 中序遍历: ";
    tree.inorder();
    cout<<endl;
    cout<<" 后序遍历: ";
    tree.postorder();
    cout<<endl;
    cout<<" 层序遍历: ";
    tree.levelorder();
    cout<<endl;
    return 0;
}


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页