以二叉链表存储二叉树,以 ‘#‘ 表示无后继结点。
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<string>
#include<algorithm>
#include<stack>
#include<queue>
using namespace std;
typedef struct BiTNode{
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
int count0=0,count1=0;
void CreateBiTree(BiTree &T); // 创建二叉树
void PrintfBiTree_x(BiTree T); // 先序遍历输出
void PrintfBiTree_z(BiTree T); // 中序遍历输出
void PrintfBiTree_h(BiTree T); // 后序遍历输出
int DepthTree(BiTree T); // 返回二叉树的深度
int NodeCount_0(BiTree T); // 返回二叉树度为0的结点数
int NodeCount_1(BiTree T); // 返回二叉树度为1的结点数
int main()
{
BiTNode *T;
CreateBiTree(T);
cout<<"先序遍历结果为:";
PrintfBiTree_x(T);
cout<<endl<<"中序遍历结果为:";
PrintfBiTree_z(T);
cout<<endl<<"后序遍历结果为:";
PrintfBiTree_h(T);
cout<<endl<<"树的深度为:"<<DepthTree(T);
cout<<endl<<"度为0的结点为个数为"<<NodeCount_0(T);
cout<<endl<<"度为1的结点为个数为"<<NodeCount_1(T);
getchar();
return 0;
}
void CreateBiTree(BiTree &T){
char ch;
cin>>ch;
if(ch=='#')
T=NULL; // 当ch== # 时,表示该结点的左子孩子或右子孩子为空。
else{
T=new BiTNode;
T->data=ch;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}
void PrintfBiTree_x(BiTree T){
if(T){
cout<<T->data<<" "; //先输出根结点, 而后递归
PrintfBiTree_x(T->lchild);
PrintfBiTree_x(T->rchild);
}
}
void PrintfBiTree_z(BiTree T){
if(T){
PrintfBiTree_z(T->lchild); //先递归往下遍历左子树
cout<<T->data<<" ";
PrintfBiTree_z(T->rchild);
}
}
void PrintfBiTree_h(BiTree T){
if(T){
PrintfBiTree_h(T->lchild); //先递归往下遍历左子树,然后右子树,最后根
PrintfBiTree_h(T->rchild);
cout<<T->data<<" ";
}
}
int DepthTree(BiTree T){
if(T==NULL) return 0;
else {
int m=DepthTree(T->lchild); //类似于后序遍历
int n=DepthTree(T->rchild);
if(m>n) return m+1;
else return n+1;
}
}
int NodeCount_0(BiTree T)// 度为0
{
if (T==NULL) return 0;
if (T->lchild==NULL&&T->rchild==NULL) //如果度为0,count0++;
{
count0++;
}
NodeCount_0(T->lchild);
NodeCount_0(T->rchild);
return count0;
}
int NodeCount_1(BiTree T)// 度为1
{
if(T==NULL) return 0;
if ((T->lchild==NULL&&T->rchild!=NULL)||(T->lchild!=NULL&&T->rchild==NULL) )
{
count1++;
}
NodeCount_1(T->lchild);
NodeCount_1(T->rchild);
return count1;
}