发布网友 发布时间:2022-04-25 12:42
共1个回答
热心网友 时间:2024-10-12 06:42
是哪种遍历方式?!!!#ifndef BinaryTree_h
#define BinaryTree_h#include <iostream.h>template<class T>
struct BTNode{
BTNode(){lChild = rChild = NULL;}
BTNode(const T& x){
element =x;
lChild = rChild = NULL;
}
BTNode(const T& x, BTNode<T>* l, BTNode<T>* r){
element = x;
lChild = l;
rChild = r;
}
T element;
BTNode<T>* lChild, *rChild;
};
template<class T>
class BinaryTree{
public:
BinaryTree(){root = NULL;}
BinaryTree(BTNode<T> *r){root = r;}
~BinaryTree(){Clear();}
bool IsEmpty()const;
bool Root(T& x)const; void MakeTree(const T& e, BinaryTree<T>& left,BinaryTree<T>& right);
void BreakTree(T& e, BinaryTree<T>& left, BinaryTree<T>& right); void PreOrder();
void InOrder();
void PostOrder();
int Size();
void Clear();
BTNode<T>* Copy();
protected:
BTNode<T>* root;
private:
void PreOrder(BTNode<T>* t);
void InOrder(BTNode<T>* t);
void PostOrder(BTNode<T>* t);
int Size(BTNode<T>* t);
void Clear(BTNode<T>* t);
BTNode<T>* Copy(BTNode<T>* t);
};template<class T>
bool BinaryTree<T>::Root(T& x)const{
if(root){
x = root->element;
return true;
}
else return false;
} template<class T>
void BinaryTree<T>::MakeTree(const T& x,BinaryTree<T>& left,BinaryTree<T>& right)
{
if(root || &left == &right) return;
root = new BTNode<T>(x, left.root, right.root);
left.root = right.root = NULL;
}
template<class T>
void BinaryTree<T>::BreakTree(T& x,BinaryTree<T>& left,BinaryTree<T>& right)
{
if(!root || &left == &right || left.root || right.root) return;
x = root->element;
left.root = root->lChild;
right.root = root->rChild;
delete root;
root = NULL;
}template<class T>
void BinaryTree<T>::PreOrder()
{
PreOrder(root);
}
template<class T>
void BinaryTree<T>::PreOrder(BTNode<T>* t)
{
if(t)
{
cout<<(t->element);
PreOrder(t->lChild);
PreOrder(t->rChild);
}
}template<class T>
void BinaryTree<T>::InOrder()
{
InOrder(root);
}
template<class T>
void BinaryTree<T>::InOrder(BTNode<T>* t)
{
if(t)
{
InOrder(t->lChild);
cout<<(t->element);
InOrder(t->rChild);
}
}
template<class T>
void BinaryTree<T>::PostOrder()
{
PostOrder(root);
}
template<class T>
void BinaryTree<T>::PostOrder(BTNode<T>* t)
{
if(t)
{
PostOrder(t->lChild);
PostOrder(t->rChild);
cout<<(t->element);
}
}template<class T>
int BinaryTree<T>::Size()
{
return Size(root);
}
template<class T>
int BinaryTree<T>::Size(BTNode<T>* t)
{
if(!t) return 0;
return Size(t->lChild) + Size(t->rChild) + 1;}template<class T>
void BinaryTree<T>::Clear()
{
Clear(root);
}
template<class T>
void BinaryTree<T>::Clear(BTNode<T>* t)
{
if(t)
{
Clear(t->lChild);
Clear(t->rChild);
cout << "delete " <<t->element << "..." << endl;
delete t;
}
}
template<class T>
BTNode<T>* BinaryTree<T>::Copy()
{ return Copy(root);
}
template<class T>
BTNode<T>* BinaryTree<T>::Copy(BTNode<T>* t)
{
if(!t) return NULL;
BTNode<T>* q = new BTNode<T>(t->element);
q->lChild = Copy(t->lChild);
q->rChild = Copy(t->rChild);
return q;
}#endif