// BinaryTree.cpp: implementation of the BinaryTree class.
//
//////////////////////////////////////////////////////////////////////
#include "BinaryTree.h"
#include "LinkedQueue.h"
#include "iostream.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
BinaryTree::~BinaryTree()
{
}
bool BinaryTree::Root(char& x) const
{
if(root){x=root->data;
return true;}
else return false;
}
void BinaryTree::MakeTree(const char& element,BinaryTree& left,BinaryTree& right){
root=new BinaryTreeNode(element,left.root,right.root);
left.root=right.root=0;
}
void BinaryTree::MakeTreenew(char *&element,BinaryTree& left,BinaryTree& right){
root=new BinaryTreeNode(element,left.root,right.root);
left.root=right.root=0;
}
void BinaryTree::BreakTree(char& element,BinaryTree& left,BinaryTree& right)
{
element=root->data;
left.root=root->LeftChild;
right.root=root->RightChild;
delete root;
root=0;
}
void BinaryTree::PreOrder(){
cout<<"前序遍历结果为:"<<endl;
PreOrder(root);
cout<<endl;
}
void BinaryTree::PreOrder(BinaryTreeNode *u){
if(u){
cout<<u->data;
PreOrder(u->LeftChild);
PreOrder(u->RightChild);
}
}
void BinaryTree::InOrder(){
cout<<"中序遍历结果为:"<<endl;
InOrder(root);
cout<<endl;
}
void BinaryTree::InOrder(BinaryTreeNode *u){
if(u){
InOrder(u->LeftChild);
cout<<u->data;
InOrder(u->RightChild);
}
}
void BinaryTree::PostOrder(){
cout<<"后序遍历结果为:"<<endl;
PostOrder(root);
cout<<endl;
}
void BinaryTree::PostOrder(BinaryTreeNode *u){
if(u){
PostOrder(u->LeftChild);
PostOrder(u->RightChild);
cout<<u->data;
}
}
void BinaryTree::LevelOrder(){
cout<<"层次遍历结果为:"<<endl;
LevelOrder(root);
cout<<endl;
}
void BinaryTree::LevelOrder(BinaryTreeNode *u){
LinkedQueue q;
while(u)
{
cout<<u->data;
if(u->LeftChild)
{
q.Add(u->LeftChild);
// cout<<u->LeftChild->data<<endl;
// cout<<"ADD LEFT"<<endl;
}
if(u->RightChild) {
q.Add(u->RightChild);
// cout<<"ADD Right"<<endl;
}
if(!q.IsEmpty()){
q.Delete(u);
//cout<<u->data<<endl;
}
else{
// cout<<"Out"<<endl;
break;
}
}
}
int BinaryTree::Height()
{
return Height(root);
}
int BinaryTree::Height(BinaryTreeNode *t)const
{
if(!t) return 0;
int hl=Height(t->LeftChild);
int hr=Height(t->RightChild);
if(hl>hr) return ++hl;
else return ++hr;
}
int BinaryTree::Count()
{
return Count(root);
}
int BinaryTree::Count(BinaryTreeNode *t)
{
if(!t) return 0;
int hl=Count(t->LeftChild);
int hr=Count(t->RightChild);
return hl+hr+1;
}