按先序遍历序列建立一个二叉树的二叉链表,统计二叉树中叶子结点个数和二叉树的深度。
#include<iostream>
using namespace std;
template <class T>
struct BTNode{
T data;
BTNode <T> * Lchild,*Rchild;
};
template <class T>
void createBinTree(BTNode<T> * & root)
{
BTNode<T>* p = root;
BTNode<T>* k;
T nodeValue;
cin>>nodeValue;
if(nodeValue=='#') {root=NULL;}
else {root=new BTNode<T>();root->data=nodeValue;createBinTree(root->Lchild);createBinTree(root->Rchild);}
}
template<class T>
int countNode(BTNode<T> * & p)
{ if(p==NULL) return 0;
else if(p->Lchild==NULL&&p->Rchild==NULL) return 1;
return countNode(p->Lchild)+countNode(p->Rchild);
}
template<class T>
int depth(BTNode<T> *& p) {
if(p == NULL) return 0;
int h1 = depth(p->Lchild); int h2 = depth(p->Rchild); if(h1>h2)return (h1+1); return h2+1; }
int main()
{
BTNode <char>*rootNode=NULL;
createBinTree(rootNode);
cout<<"leafs="<<countNode(rootNode)<<endl;
cout<<"Depth="<<depth(rootNode)<<endl;
}