一、实验要求:
-
理解和掌握二叉树的基本性质,学会创建给定形式的二叉树;
-
熟练掌握二叉树的递归和非递归遍历算法的实现。
二、实验内容:
用递归的方法实现以下算法:
1)以二叉链表表示二叉树,建立一棵二叉树;
2)输出二叉树的中序遍历、前序遍历、后序遍历结果;3个函数
3)统计二叉树的深度、结点个数、统计二叉树的叶结点个数;3个函数;
#include<iostream>
#include<string>
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
using namespace std;
#define OK 1
typedef int Status;
int flag = 0;
typedef struct BiLNode
{
string data;
struct BiLNode* RChild;
struct BiLNode* LChild;
}BiLNode,*BiTree;
void InitList(BiTree l)
{
l = new BiLNode;
l->data = "";
l->LChild = NULL;
l->RChild = NULL;
}
Status CreateBiTree(BiTree &T)
{
char ch;
cout << "请输入:" << endl;
cin >> ch;
if (ch == '#')
{
T = NULL;
return OK;
}
else
{
T = new BiLNode;
if (T)
{
T->data = ch;
CreateBiTree(T->LChild);
CreateBiTree(T->RChild);
}
else
{
cout << "内存分配出错";
exit(0);
}
}
}
void PreOrder(BiTree root)
{
if (root != NULL)
{
cout << root->data;
PreOrder(root->LChild);
PreOrder(root->RChild);
}
}
void InOrder(BiTree root)
{
if (root != NULL)
{
InOrder(root->LChild);
cout << root->data;
InOrder(root->RChild);
}
}
void PostOrder(BiTree root)
{
if (root != NULL)
{
PostOrder(root->LChild);
PostOrder(root->RChild);
cout << root->data;
}
}
Status Count_1(BiTree T)//统计二叉树节点个数
{
if (T == NULL)return 0;
else return 1 + Count_1(T->LChild) + Count_1(T->RChild);
}
Status Count_2(BiTree T)//计算二叉树叶子结点个数
{
if (T == NULL)
return 0;
else if ((T->LChild == NULL) && (T->RChild == NULL))
return 1 + Count_2(T->LChild) + Count_2(T->RChild);
}
void judge(BiTree p, int level)
{
if (p == NULL)
return;
if (level > flag)
flag = level;
if (p->LChild != NULL)
judge(p->LChild, level + 1);
if (p->RChild != NULL)
judge(p->RChild, level + 1);
}
int main()
{
BiTree bt;
bt = NULL;
InitList(bt);
CreateBiTree(bt);
PreOrder(bt);
cout << endl;
InOrder(bt);
cout << endl;
PostOrder(bt);
cout << endl;
Count_1(bt);
cout << endl;
Count_2(bt);
cout << endl;
judge(bt, 1);
cout << flag;
return 0;
}