#include<iostream>
using namespace std;
struct BTree
{
char data;
BTree *lchild;
BTree *rchild;
};
//创建二叉树
void CreateTree(BTree * &T)
{
char ch;
cin>>ch;
if(ch=='#') {return;}
else
{
T=new BTree;
if(!T) cout<<"生成结点错误!"<<endl;
T->data=ch;
T->lchild=NULL;
T->rchild=NULL;
CreateTree(T->lchild);
CreateTree(T->rchild);
}
}
//递归,先序遍历
void Preorder(BTree *temp)
{
if(temp!=NULL)
{
cout<<temp->data<<" ";
Preorder(temp->lchild);
Preorder(temp->rchild);
}
}
//递归,中序遍历
void Inorder(BTree *temp)
{
if(temp!=NULL)
{
Inorder(temp->lchild);
cout<<temp->data<<" ";
Inorder(temp->rchild);
}
}
//递归,后序遍历
void Postorder(BTree *temp)
{
if(temp!=NULL)
{
Postorder(temp->lchild);
Postorder(temp->rchild);
cout<<temp->data<<" ";
}
}
//递归计算二叉树节点的个数
int count(BTree *temp)
{
if(temp==NULL)
return 0;
else
return count(temp->lchild)+count(temp->rchild)+1;
}
//求二叉树叶子的个数
int findleaf(BTree *temp)
{
int n=0;
if(temp==NULL)return 0;
else
{
if(temp->lchild==NULL&&temp->rchild==NULL)
return n+=1;
else
{
n+=findleaf(temp->lchild);
n+=findleaf(temp->rchild);
}
return n;
}
}
//求二叉树中度数为1的结点数量
int find_1_node(BTree *temp)
{
int m=0;
if(temp==NULL)return 0;
else
{
if(temp->lchild!=NULL&&temp->rchild!=NULL)
{
m+=find_1_node(temp->lchild);
m+=find_1_node(temp->rchild);
}
if(temp->lchild!=NULL&&temp->rchild==NULL)
{
m+=1;
m+=find_1_node(temp->lchild);
}
if(temp->lchild==NULL&&temp->rchild!=NULL)
{
m+=1;
m+=find_1_node(temp->rchild);
}
}
return m;
}
int main()
{
BTree *root=NULL;
cout<<"创建二叉树:";
CreateTree(root);
cout<<endl<<"先序遍历序列: "<<endl;
Preorder(root);cout<<endl;
cout<<endl<<"中序遍历序列: "<<endl;
Inorder(root);cout<<endl;
cout<<endl<<"后序遍历序列: "<<endl;
Postorder(root);cout<<endl;cout<<endl;
cout<<"二叉树节点个数: "<<count(root)<<endl;
cout<<"二叉树叶子个数:"<<findleaf(root)<<endl;
cout<<"二叉树中度数为1的结点的数量为:"<<find_1_node(root)<<endl;
return 0;
}
