注意先序建立时调用的是结点指针的地址
#include<iostream>
using namespace std;
typedef struct bitnode {
char data;
struct bitnode* lchild, * rchild;
}bitnode,*bitree;//定义结点
int i;//全局变量i用于计数结点数
void createeBITREE(bitree *s)//前序建立二叉链表,#代表空
{
char ch;
cin >>ch;
if(ch=='#')
*s=NULL;
else
{
*s = new bitnode;
(*s)->data = ch;
i++;
createeBITREE(&(*s)->lchild);
createeBITREE(&(*s)->rchild);
}
}
void inordertree(bitree T)//中序访问二叉树
{
if (T)
{
inordertree(T->lchild);
cout << T->data;
inordertree(T->rchild);
}
}
void tree(bitree T)//前序访问二叉树
{
if (T)
{
cout << T->data;
tree(T->lchild);
tree(T->rchild);
}
}
void hitree (bitree T)//后序访问二叉树
{
if (T)
{
hitree(T->lchild);
hitree(T->rchild);
cout << T->data;
}
}
int m = 0;//叶子结点数
void countleaf(bitree T)//叶子结点数计算
{
if (T != NULL)
{
if (T->lchild == NULL && T->rchild == NULL)
++m;
countleaf(T->lchild);
countleaf(T->rchild);
}
}
int main()
{
bitree T=NULL;
cout << "请输入前序二叉树字符:" << endl;
createeBITREE(&T);
cout << "结点个数为:" << i << endl;
countleaf(T);
cout << "叶子结点个数为:" << m<< endl;
cout << "中序遍历二叉树:" ;
inordertree(T);cout << endl;
cout << "前序遍历二叉树:";
tree(T);cout << endl;
cout << "后序遍历二叉树:" ;
hitree(T);cout << endl;
return 0;
}
结果显示
请输入前序二叉树字符:
12###
结点个数为:2
叶子结点个数为:1
中序遍历二叉树:21
前序遍历二叉树:12
后序遍历二叉树:21
C++实现先序建立二叉树、遍历、输出结点个数、叶子结点个数
最新推荐文章于 2022-06-13 15:24:04 发布