求二叉樹的最大高度完整程式碼C++
我這個和之前寫的模板用的是一個,這裡求了二叉樹的高度,寬度沒寫出來,
大家就勉強看一下吧
#include <iostream>
#include <string>
#include <queue>
usingnamespacestd;
int maxWidth=2;
typedefint KeyType;
class BinSTree {
public:
KeyType data;
BinSTree *root;
BinSTree *leftchild;
BinSTree *rightchild;
BinSTree() {
root
leftchild=NULL;
rightchild=NULL;
}
~BinSTree() {
}
BinSTree *BSTreeSearch(KeyType k,BinSTree *&p);
void BSTreeInsert(KeyType k);
int Height(BinSTree *a);
int BSTreeLevelTraverse(BinSTree *bt);
};
BinSTree *BinSTree::BSTreeSearch(KeyType k,BinSTree *&p)
{
BinSTree *q=NULL;
q=root;
while(q)
{
p=q;
if(q->data==k)
returnp;
elseif(q->data>k)
q=q->leftchild;
else
q=q->rightchild;
}
returnNULL;
}
void BinSTree::BSTreeInsert(KeyType k)
{
BinSTree *p=NULL,*q=NULL;
q=root;
if(BSTreeSearch
{
BinSTree *r=new BinSTree;
r->data=k;
if(q==NULL)//根結點為空
{
root=r;
return ;
}
if(p&&k<p->data)
p->leftchild=r;
elseif(p&&k>p->data)
p->rightchild=r;
}
}
int BinSTree::Height(BinSTree *a) { //求二叉樹的最大高度
if(a==NULL)
return0;
int lheight=Height(a->leftchild);
int rheight=Height(a->rightchild);
return max(lheight,rheight)+1;
}
intBinSTree::BSTreeLevelTraverse(BinSTree *bt) //求二叉樹的最大寬度,沒做出來。。。
{
deque<BinSTree*> q;
int maxWidth = 1;
q.push_back(bt);
while(true) {
int length=q.size();
cout<<length<<endl;
if(length=0)
break;
while(length>0) {
BinSTree* pTemp=q.front();
q.pop_front();
--length;
if(pTemp->leftchild)
q.push_back(pTemp->leftchild);
if(pTemp->rightchild)
q.push_back(pTemp->rightchild);
}
maxWidth=maxWidth>q.size()?maxWidth:q.size();
}
return maxWidth;
}
int main() {
int a[13]={34,18, 76,13,12,11,52, 82,16, 67,58, 73,72 };
BinSTree bst;
for(int i=0;i<13;i++)
{
bst.BSTreeInsert(a[i]);
}
cout<<bst.Height(bst.root)<<endl;
//cout<<bst.BSTreeLevelTraverse(bst.root)<<endl;
//cout<<maxWidth<<endl;
return0;
}