二叉树简单实现

#include<iostream>
#include<string>
using namespace std;
template<typename T>
struct BinNode
{
 T data;
 BinNode<T>* leftChild;
 BinNode<T>* rightChild;
};

template<typename T>
class BinTree
{
public:
 BinTree();
 ~BinTree();

 void PreOrder(const BinNode<T>*root)const;
 void PreOrder()const;

 void PosOrder(const BinNode<T>*root)const;
 void PosOrder()const;

 void LeverOrder(const BinNode<T>*root)const;
 void LeverOrder()const;

 
private:
 BinNode<T>* root;
 BinNode<T>* Create();
 void Release(BinNode<T>* );
 BinNode<T>* GetRoot()const;

};

template<typename T>
BinTree<T>::BinTree()
{
 root=Create();
}

template<typename T>
BinTree<T>::~BinTree()
{
 Release(root);
}

template<typename T>
void BinTree<T>::PreOrder(const BinNode<T>*root)const
{ if(root==0)
 return;
 cout<<root->data<<" ";
 PreOrder(root->leftChild);
 PreOrder(root->rightChild);
}

template<typename T>
void BinTree<T>::PreOrder()const
{
 PreOrder(root);
}

template<typename T>
void BinTree<T>::PosOrder(const BinNode<T>*root)const
{if(root==0)
 return;
 
 PreOrder(root->leftChild);
 PreOrder(root->rightChild);
 cout<<root->data<<" ";
}

template<typename T>
void BinTree<T>::PosOrder()const
{
 PosOrder(root);
}

template<typename T>
void BinTree<T>::LeverOrder(const BinNode<T>*root)const
{
}

template<typename T>
BinNode<T>* BinTree<T>::GetRoot()const
{
 return root;
}

template<typename T>
BinNode<T>* BinTree<T>::Create()
{ static long i=0;
 ++i;
 bool flag=true;
 BinNode<T>* root;
 T ch;
 if(i!=1)
 { 
  char ch;
  cout<<"Continue?(t or f?)";
  cin>>ch;
  if(ch=='t')
   flag=true;
  else if(ch=='f')
   flag=false;
  else throw "Wrong infomation";
 }

 if(flag)
 {

  
  cout<<"Please input data for binary tree node\n";
  cin>>ch;
  root=new BinNode<T>;
  root->data=ch;
  root->leftChild=Create();
  root->rightChild=Create();  
 }
 else root=0;
 return root;
 
}

template<typename T>
void BinTree<T>::Release(BinNode<T>*root)
{
 if(root==0)
  return ;
 Release(root->leftChild);
 Release(root->rightChild);
}

你可能感兴趣的:(二叉树)