您的位置:首页 > 其它

二叉树的基本遍历操作

2011-08-25 19:22 435 查看
#include <queue>
#include <iostream>
using namespace std;

#define QSIZE 100
struct BTree

{
int value;
struct BTree* lChild;
struct BTree* rChild;
};

void VisitNode(BTree * T)
{
cout<<T->value<<" ";
}
BTree * Insert(BTree* T, int value) //T is the root of binary tree
{
if(T == NULL)
{
T = new BTree;
if( T == NULL)
cout<<"Malloc Failed."<<endl;
else
{
T->value  = value;
T->lChild = T->rChild = NULL;
}
}
else if(value < T->value)
T->lChild = Insert(T->lChild,value);
else if(value > T->value)
T->rChild = Insert(T->rChild, value);
return T;
}

BTree* MakeEmpty(BTree* T)
{
if(T != NULL)
{
MakeEmpty(T->lChild);
MakeEmpty(T->rChild);
delete T;
}
return NULL;
}

void LevelTraversal(BTree * T)
{
if(T == NULL)
return;
queue<BTree> Queue;
Queue.push(*T);
while(!Queue.empty())
{
VisitNode(&Queue.front());
if(Queue.front().lChild != NULL)
Queue.push(*Queue.front().lChild);
if(Queue.front().rChild != NULL)
Queue.push(*Queue.front().rChild);
Queue.pop();
}
}

void PreOrder(BTree * T)
{
if(T == NULL)
return;
VisitNode(T);
PreOrder(T->lChild);
PreOrder(T->rChild);
}

void InOrder(BTree * T)
{
if(T == NULL)
return;
InOrder(T->lChild);
VisitNode(T);
InOrder(T->rChild);
}

void PosOrder(BTree * T)
{
if(T == NULL)
return;
PosOrder(T->lChild);
PosOrder(T->rChild);
VisitNode(T);
}

int HeightofBTree(BTree * T)
{
if(T == NULL)
return 0;

int hLeft = HeightofBTree(T->lChild);
int hRight = HeightofBTree(T->rChild);
return (hLeft > hRight ? hLeft : hRight) + 1;
}

int main()
{
BTree* T = NULL;
T = Insert(T,45);
T = Insert(T,21);
T = Insert(T,65);
T = Insert(T,10);
T = Insert(T,50);
T = Insert(T,70);
T = Insert(T,24);

cout<<"Level Traversal:";
LevelTraversal(T);
cout<<endl;

cout<<"Preorder Traversal:";
PreOrder(T);
cout<<endl;

cout<<"Inorder Traversal:";
InOrder(T);
cout<<endl;

cout<<"Posorder Traversal:";
PosOrder(T);
cout<<endl;

cout<<"Height of BTree is "<<HeightofBTree(T);

MakeEmpty(T);
cout<<endl;
return 0;
}


  建立一个二分排序树,注意二叉树内存空间的递归释放。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐