const int maxn = (int)1e3 + 5;
template<class T>
class Myque
{
private:
T data[maxn];
int f, r;
public:
Myque() :f(0), r(0){}
bool empty(){ return f == r; }
T front(){ return data[f]; }
void pop(){ f = (f + 1) % maxn; }
void push(T t){ data[r] = t; r = (r + 1) % maxn; }
};
// 二叉树BinTree
typedef char Elemtype;
typedef struct BTNode
{
Elemtype data;
BTNode *left, *right;
}BTNode, *BinTree;
遍历操作
void visit(BinTree T) //具体自己实现
{
cout << T->data << " " ;
}
void InorderTraversal(BinTree BT) //中根遍历
{
if (!BT)return;
InorderTraversal(BT->left);
visit(BT);
InorderTraversal(BT->right);
}
void PreorderTraversal(BinTree BT) //先根遍历
{
if (!BT)return;
visit(BT);
PreorderTraversal(BT->left);
PreorderTraversal(BT->right);
}
void PostorderTraversal(BinTree BT) //后根遍历
{
if (!BT)return;
PostorderTraversal(BT->left);
PostorderTraversal(BT->right);
visit(BT);
}
void LevelorderTraversal(BinTree BT) //层序遍历
{
if (!BT)return;
Myque<BinTree> que; //需要辅助队列来实现
BinTree p;
que.push(BT);
while (!que.empty())
{
p = que.front(); que.pop();
visit(p);
if (p->left)que.push(p->left);
if (p->right)que.push(p->right);
}
}
创建操作
char ch; //先根
void CreateBinTree(BinTree &T) // ABC##DE#G##F###
{
cin >> ch;
if (ch == '#')T = NULL;
else
{
T = (BinTree)malloc(sizeof(BTNode));
T->data = ch;
CreateBinTree(T->left);
CreateBinTree(T->right);
}
}
复制操作
void BinTreeCopy(BinTree &New,BinTree T)
{
if (T == NULL)New = NULL;
else
{
New = (BinTree)malloc(sizeof(BTNode));
New->data = T->data;
BinTreeCopy(New->left, T->left);
BinTreeCopy(New->right, T->right);
}
}
深度
int BinTreeHeight(BinTree BT)
{
if (BT == NULL)return 0;
int l = BinTreeHeight(BT->left)+1;
int r = BinTreeHeight(BT->right)+1;
return l > r ? l : r;
}
结点个数
int BinTreeNode(BinTree BT)
{
if (BT == NULL)return 0;
return 1 + BinTreeNode(BT->left) + BinTreeNode(BT->right);
}