这一篇写一下(1)求二叉树高度
(2)求叶子节点数
(3)层次遍历
这是上一篇博文,关于递归/非递归先中后序遍历二叉树:
http://blog.csdn.net/dala_da/article/details/79234619
#include<iostream>
#include<stdlib.h>
#include<queue>
using namespace std;
typedef struct BiTNode{
char data;
BiTNode *lchild, *rchild;
}BiTNode, *BiTree;
void Input_BiTree(BiTree &exa){
char data;
cin>>data;
if(data=='#'){
exa=NULL;
return;
}
else{
exa=(BiTree)malloc(sizeof(BiTNode));
exa->data=data;
Input_BiTree(exa->lchild);
Input_BiTree(exa->rchild);
}
}
int GetDepth(BiTree exa){
BiTree T=exa;
if(T==NULL)
return 0;
else{
int depth_rchild=GetDepth(T->lchild); //该节点左子树深度
int depth_lchild=GetDepth(T->rchild); //该节点右子树深度
int depth = depth_rchild>depth_lchild ? depth_rchild : depth_lchild;
return ++depth;
}
}
int GetLeafNodeCount(BiTree exa){
BiTree T=exa;
if(T==NULL)
return 0;
else if(T!=NULL && T->rchild==NULL && T->lchild==NULL) //说明是叶子节点,返回1
return 1;
else
return GetLeafNodeCount(T->lchild)+GetLeafNodeCount(T->rchild);
}
void LevelOrder(BiTree exa){
BiTree root=exa;
BiTree LevelFirst, LevelEnd; //分别表示每一层的最左面节点和最右面节点
queue<BiTree> p;
p.push(root);
LevelFirst=LevelEnd=p.front();
while(1){
while(LevelFirst<=LevelEnd){
if(LevelFirst->lchild!=NULL) //不为空则压入队列。由于队列先进先出的性质,低层节点肯定比高层节点先pop出来
p.push(LevelFirst->lchild);
if(LevelFirst->rchild!=NULL)
p.push(LevelFirst->rchild);
cout<<LevelFirst->data<<" ";
p.pop();
if(p.empty()) //上一步pop完成后,有可能遍历完最后一个节点,则此时queue为空,层次遍历结束
return;
LevelFirst=p.front();
}
LevelEnd=p.back();
}
}
int main(){
BiTree T;
int depth, LeafNodeCount;
cout<<"请输入二叉树(按照先序)"<<endl;
Input_BiTree(T);
depth=GetDepth(T);
cout<<"depth="<<depth<<endl;
LeafNodeCount=GetLeafNodeCount(T);
cout<<"LeafNodeCount="<<LeafNodeCount<<endl;
cout<<"层次遍历为:"<<endl;
LevelOrder(T);
return 0;
}