#include <iostream>;
#include <queue>;
using namespace std;
typedef char DATA;
typedef struct BitTree
{
DATA data;
BitTree *lChild, *rChild;
}BitTree, *BitNode;
class CBitTree
{
public:
BitTree* node;
CBitTree()
{
node = NULL; //node初始化爲空
}
void CreateTree(BitTree**node) //創建樹
{
DATA data = 0;
cin >> data;
if (data == '#')
{
*node = NULL;
}
else
{
*node = new BitTree;
(*node)->data = data;
cout << "輸入左子樹數據" << endl;
CreateTree(&(*node)->lChild);
cout << "輸入右子樹數據" << endl;
CreateTree(&(*node)->rChild);
}
}
void DLRSearch(BitTree**node) //前序遍歷
{
if ((*node) != NULL)
{
cout << (*node)->data << endl;
rootFirtSearch(&(*node)->lChild);
rootFirtSearch(&(*node)->rChild);
}
}
void LDRSearch(BitTree**node) //中序遍歷
{
if ((*node) != NULL)
{
rootFirtSearch(&(*node)->lChild);
cout << (*node)->data << endl;
rootFirtSearch(&(*node)->rChild);
}
}
void LRDSearch(BitTree**node) //後序遍歷
{
if ((*node) != NULL)
{
rootFirtSearch(&(*node)->lChild);
rootFirtSearch(&(*node)->rChild);
cout << (*node)->data << endl;
}
}
void levelSearch() //層序遍歷
{
queue<BitNode> q;
q.push(node);
while (!q.empty())
{
node = q.front();
cout << node->data << endl;
if (node->lChild)
{
q.push(node->lChild);
}
if (node->rChild)
{
q.push(node->rChild);
}
q.pop();
}
}
~CBitTree()
{
DeleteTree(&node); //析構函數自動刪除二叉樹所佔堆空間
}
private:
void DeleteTree(BitTree**node) //二叉樹刪除
{
if (*node != NULL)
{
BitTree* lChild = (*node)->lChild;
BitTree* rChild = (*node)->rChild;
delete *node;
*node = NULL;
DeleteTree(&lChild);
DeleteTree(&rChild);
}
}
};
二叉樹的存儲,創建,以及四種遍歷,刪除
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.