您的位置:首页 > 其它

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

2015-06-24 12:14 246 查看

二叉树的遍历

主要代码片段

#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

输出:



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

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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: