二叉树链表的前,中,后序遍历

来源:互联网 发布:在安卓手机上编程 编辑:程序博客网 时间:2024/05/21 06:01

二叉树的遍历

主要代码片段

#include<iostream>using namespace std;struct BinNode{    char data;    BinNode *left;    BinNode *right;};class Tree{private:    BinNode *head;    BinNode *t;public:    Tree(){ head = NULL; }    BinNode *CreateNewBinNode(char data);      //创建一个新节点,节点的内容为data,左右节点为空    BinNode *GetHead(){ return head; }  //获取头结点    bool Insert(char data);             //插入节点    void Visit(BinNode *node);          //根据节点来访问起内容    void PreOrder(BinNode *t);          //前序遍历    void InOrder(BinNode *t);           //中序遍历    void PostOrder(BinNode *t);         //后序遍历};int main(){    char c;    Tree BinTree;    for (int i = 0; i < 7; i++)    {        cin>>c;        BinTree.Insert(c);    }    BinNode *t = BinTree.GetHead();    cout << "\n前序遍历:" << endl;    BinTree.PreOrder(t);    cout << "\n中序遍历:" << endl;    t = BinTree.GetHead();    BinTree.InOrder(t);    cout << "\n后序遍历:" << endl;    t = BinTree.GetHead();    BinTree.PostOrder(t);    cout << endl;    return 0;}BinNode *Tree::CreateNewBinNode(char data){    BinNode *Node = new BinNode;    if (Node == NULL)    {        return NULL;    }    else    {        Node->data = data;        Node->left = NULL;        Node->right = NULL;        return Node;    }}bool Tree::Insert(char data){    if (head == NULL)       //先判断头结点是否为空,先根是否为空    {        head = new BinNode;        head->data = data;        head->right = NULL;        head->left = NULL;        t = head;        return true;    }    BinNode *Node = CreateNewBinNode(data);    if (Node == NULL)           {        return false;    }    BinNode *t = head;    while (1)                       //顺序插入节点    {        if (t->data == Node->data)        {            return true;        }        if (t->data > Node->data) //若节点小于则插入左边        {            if (t->left == NULL)            {                t->left = Node;                return true;            }            t = t->left;        }        else                     //大于则插入右边        {            if (t->right == NULL)            {                t->right = Node;                return true;            }            t = t->right;        }    }}void Tree::Visit(BinNode *node){    cout << node->data << "  ";}void Tree::PreOrder(BinNode *t){    if (t == NULL)    {        return;    }    Visit(t);    PreOrder(t->left);    PreOrder(t->right);}void Tree::InOrder(BinNode *t){    if (t == NULL)    {        return;    }    InOrder(t->left);    Visit(t);    InOrder(t->right);}void Tree::PostOrder(BinNode *t){    if (t == NULL)    {        return;    }    PostOrder(t->left);    PostOrder(t->right);    Visit(t);}

运行结果:

输入:e b f a d g c

输出:

二叉树遍历

本代码为作者原创,若有引用请标明出处

若有疑问敬请留言,或者私信

0 0
原创粉丝点击