#include<iostream>
#include<cstdio>
#include<stdlib.h>
using namespace std;
typedef struct BiTnode
{
int data;
struct BiTnode* Lchild, * Rchild;
}BiTnode, * BiTree;
int create(BiTree* T)
{
int ch, temp;
cin >> ch;
temp = getchar();
if (ch == 0)
* T = NULL;
else
{
*T = (BiTree)malloc(sizeof(BiTnode));
if (!(*T))
exit(-1);
else
{
(*T)->data = ch;
cout << "请输入" << ch << "的左节点的值:";
create(&(*T)->Lchild);
cout << "请输入" << ch << "的右节点的值:";
create(&(*T)->Rchild);
}
}
return 1;
}
void Traverse(BiTree T)//前序遍历二叉树
{
if (NULL == T)
return;
else
{
cout << T->data << " ";
Traverse(T->Lchild);
Traverse(T->Rchild);
}
}
void midTraverse(BiTree T)//中序遍历二叉树
{
if (T == NULL)
return;
midTraverse(T->Lchild);
cout << T->data << " ";
midTraverse(T->Rchild);
}
void lasTraverse(BiTree T)//后序遍历二叉树
{
if (T == NULL)
return;
lasTraverse(T->Lchild);
lasTraverse(T->Rchild);
cout << T->data << " ";
}
int TreeDeep(BiTree T)//二叉树的深度
{
int deep = 0;
if (T)
{
int leftdeep = TreeDeep(T->Lchild);
int rightdeep = TreeDeep(T->Rchild);
if (leftdeep >= rightdeep)
deep = leftdeep + 1;
else
deep = rightdeep + 1;
}
return deep;
}
int Leafcount(BiTree T, int& num)//求二叉树叶子节点的个数
{
if (T)
{
if (T->Lchild == NULL && T->Rchild == NULL)
num++;
Leafcount(T->Lchild, num);
Leafcount(T->Rchild, num);
}
return num;
}
int main()
{
BiTree T;
BiTree* p = (BiTree*)malloc(sizeof(BiTree));
int deepth = 0, num = 0;
cout << "请输入第一个节点的值,0代表没有叶节点" << endl;
create(&T);
cout << "先序遍历二叉树" << endl;
Traverse(T);
cout << endl;
cout << "中序遍历二叉树" << endl;
midTraverse(T);
cout << endl;
cout << "后序遍历二叉树" << endl;
lasTraverse(T);
cout << endl;
cout << "数的深度为:" << TreeDeep(T) << endl;
cout << endl;
cout << "二叉树的叶子节点的个数为:" << Leafcount(T, num) << endl;
cout << endl;
system("pause");
return 0;
}
二叉树的遍历
于 2022-05-07 15:00:48 首次发布