按照教材中关于二叉树的抽象数据类型定义,采用二叉链表存储结构,编程实现二叉树的各种基本操作,并通过主函数调用,简单测试各基本函数的正确性。 比如:二叉树的基本操作可包括: (1) void InitBT( BTreeNode *&BT ) //初始化二叉树BT (2) void CreateBT( BTreeNode *&BT, char *a ) //根据字符串a所给出二叉树的描述,建立二叉链表存储结构 (3) int EmptyBT( BTreeNode *BT) //检查二叉树BT是否为空,空返回1,否则返回0 (4) int DepthBT( BTreeNode *BT) //求二叉树BT的深度并返回该值 (5) int NodeCount(BTreeNode *BT) //求二叉树BT的总结点个数 (6) void PreOrder( BTreeNode *BT) //先序遍历递归算法 (7) void InOrder( BTreeNode *BT) //中序遍历递归算法 (8) void PostOrder( BTreeNode *BT) //后序遍历递归算法 (9) int FindBT( BTreeNode *BT, ElemType x) //查找二叉树BT中值为x的结点,若查找成功返回1,否则返回0 (10)void DestroyBT( BTreeNode *&BT ) //销毁二叉树BT
时间: 2023-12-10 07:38:48 浏览: 53
以下是二叉树基本操作的代码实现:
```
#include <iostream>
#include <cstring>
using namespace std;
typedef char ElemType;
typedef struct BTreeNode {
ElemType data;
struct BTreeNode *lchild, *rchild;
} BTreeNode, *BT;
void InitBT(BT &BT) {
BT = NULL;
}
void CreateBT(BT &BT, char *a, int &i) {
if (a[i] == '\0') {
return;
}
if (a[i] == '#') {
BT = NULL;
} else {
BT = new BTreeNode;
BT->data = a[i];
CreateBT(BT->lchild, a, ++i);
CreateBT(BT->rchild, a, ++i);
}
}
int EmptyBT(BT BT) {
return BT == NULL;
}
int DepthBT(BT BT) {
if (BT == NULL) {
return 0;
}
int left_depth = DepthBT(BT->lchild);
int right_depth = DepthBT(BT->rchild);
return max(left_depth, right_depth) + 1;
}
int NodeCount(BT BT) {
if (BT == NULL) {
return 0;
}
return NodeCount(BT->lchild) + NodeCount(BT->rchild) + 1;
}
void PreOrder(BT BT) {
if (BT != NULL) {
cout << BT->data << " ";
PreOrder(BT->lchild);
PreOrder(BT->rchild);
}
}
void InOrder(BT BT) {
if (BT != NULL) {
InOrder(BT->lchild);
cout << BT->data << " ";
InOrder(BT->rchild);
}
}
void PostOrder(BT BT) {
if (BT != NULL) {
PostOrder(BT->lchild);
PostOrder(BT->rchild);
cout << BT->data << " ";
}
}
int FindBT(BT BT, ElemType x) {
if (BT == NULL) {
return 0;
}
if (BT->data == x) {
return 1;
}
return FindBT(BT->lchild, x) || FindBT(BT->rchild, x);
}
void DestroyBT(BT &BT) {
if (BT != NULL) {
DestroyBT(BT->lchild);
DestroyBT(BT->rchild);
delete BT;
BT = NULL;
}
}
int main() {
BT BT;
InitBT(BT);
char a[100];
cin >> a;
int i = 0;
CreateBT(BT, a, i);
cout << EmptyBT(BT) << endl;
cout << DepthBT(BT) << endl;
cout << NodeCount(BT) << endl;
PreOrder(BT);
cout << endl;
InOrder(BT);
cout << endl;
PostOrder(BT);
cout << endl;
cout << FindBT(BT, 'E') << endl;
DestroyBT(BT);
return 0;
}
```
上述代码实现了二叉树的基本操作,可以根据输入的字符串构造二叉树,并对其进行各种操作。
阅读全文