二叉树的其他算法:
描述
要求:
1.采用二叉链表的方式进行存储
2.构造一个二叉树类
实现以下算法:
1.统计树中节点个数
2.统计树中叶子节点个数
3.统计树的高度
4.二叉树左右子树的交换
#include<iostream>
using namespace std;
template <typename T>
struct BiNode
{
T data;
BiNode<T> *lchild,*rchild;
};
template <typename T>
class BiTree
{
private:
BiNode<T>*root;
BiNode<T>*Creat();
void PreOrder(BiNode<T> *root);
void InOrder(BiNode<T> *root);
void PostOrder(BiNode<T> *root);
int Count(BiNode<T> *root);
int Height(BiNode<T> *root);
int Leaf(BiNode<T> *root);
void Change(BiNode<T> *root);
public:
void PreOrder(){PreOrder(root);}
BiTree(){root=Creat();}
int Count(){return Count(root);}
int Height(){return Height(root);}
int Leaf(){return Leaf(root);}
void Change(){Change(root);}
};
template <typename T>
BiNode<T>*BiTree<T>::Creat()
{
BiNode<T> *root;
char ch;
cin>>ch;
if(ch=='#') root=NULL;
else
{
root=new BiNode<T>;
root->data=ch;
root->lchild=Creat();
root->rchild=Creat();
}
return root;
}
template <typename T>
void BiTree<T>::PreOrder(BiNode<T> *root)
{
if(root==NULL) return;
else
{
cout<<root->data;
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}
template <typename T>
int BiTree<T>::Count(BiNode<T>*root)
{
int num=0;
if(root==NULL)return 0;
num=Count(root->rchild)+Count(root->lchild)+1;
return num;
}
template <typename T>
int BiTree<T>::Height(BiNode<T>*root)
{
int lheight=0;
int rheight=0;
if(root==NULL)return 0;
lheight=Height(root->lchild);
rheight=Height(root->rchild);
if(lheight>rheight)
return lheight+1;
else
return rheight+1;
}
template <typename T>
int BiTree<T>::Leaf(BiNode<T>*root)
{
int num=0;
if(root==NULL)
num=0;
else if(root->lchild==NULL&&root->rchild==NULL)
num=1;
else
{
num=Leaf(root->lchild)+Leaf(root->rchild);
}
return num;
}
template <typename T>
void BiTree<T>::Change(BiNode<T>*root)
{
if(!root) return;
Change(root->lchild);
Change(root->rchild);
BiNode<T>*a;
a=root->lchild;
root->lchild=root->rchild;
root->rchild=a;
}
int main()
{
string a;
do
{
BiTree<char> ob;
cout<<ob.Count();
cout<<endl;
cout<<ob.Leaf();
cout<<endl;
cout<<ob.Height();
cout<<endl;
ob.Change();
ob.PreOrder();
cout<<endl;
cin>>a;
}while (a!="N");
}