设计二叉排序树类实现插入结点、构造二叉排序树、输出查找路径、判断是否二叉排序树4个成员函数。
时间: 2023-11-19 19:02:59 浏览: 36
下面是一个简单的二叉排序树类实现,包含插入节点、构造二叉排序树、输出查找路径和判断是否二叉排序树等四个成员函数。
```c++
#include <iostream>
using namespace std;
// 二叉排序树节点定义
struct BSTNode {
int data; // 数据域
BSTNode* left; // 左子树指针
BSTNode* right; // 右子树指针
};
class BST {
public:
BST(); // 构造函数
~BST(); // 析构函数
bool Insert(int key); // 插入节点
void PrintPath(int key); // 输出查找路径
bool IsBST(); // 判断是否二叉排序树
private:
BSTNode* root; // 根节点指针
bool Insert(BSTNode*& node, int key);
void Destroy(BSTNode* node);
void PrintPath(BSTNode* node, int key);
bool IsBST(BSTNode* node, int min, int max);
};
// 构造函数
BST::BST() {
root = NULL;
}
// 析构函数
BST::~BST() {
Destroy(root);
}
// 插入节点
bool BST::Insert(int key) {
return Insert(root, key);
}
bool BST::Insert(BSTNode*& node, int key) {
if (node == NULL) {
// 当前节点为空,新建节点并赋值
node = new BSTNode;
node->data = key;
node->left = NULL;
node->right = NULL;
return true;
}
else if (key == node->data) {
// 节点已存在
return false;
}
else if (key < node->data) {
// 插入左子树
return Insert(node->left, key);
}
else {
// 插入右子树
return Insert(node->right, key);
}
}
// 输出查找路径
void BST::PrintPath(int key) {
PrintPath(root, key);
}
void BST::PrintPath(BSTNode* node, int key) {
if (node == NULL) {
// 未找到节点
cout << "Node " << key << " not found!" << endl;
return;
}
else if (key == node->data) {
// 找到节点
cout << key << endl;
return;
}
else if (key < node->data) {
// 在左子树中查找
cout << node->data << "->";
PrintPath(node->left, key);
}
else {
// 在右子树中查找
cout << node->data << "->";
PrintPath(node->right, key);
}
}
// 判断是否二叉排序树
bool BST::IsBST() {
return IsBST(root, INT_MIN, INT_MAX);
}
bool BST::IsBST(BSTNode* node, int min, int max) {
if (node == NULL) {
return true;
}
else if (node->data < min || node->data > max) {
return false;
}
else {
return IsBST(node->left, min, node->data) && IsBST(node->right, node->data, max);
}
}
// 销毁二叉排序树
void BST::Destroy(BSTNode* node) {
if (node != NULL) {
Destroy(node->left);
Destroy(node->right);
delete node;
}
}
```
使用示例:
```c++
int main() {
BST bst;
bst.Insert(5);
bst.Insert(3);
bst.Insert(7);
bst.Insert(2);
bst.Insert(4);
bst.Insert(6);
bst.Insert(8);
bst.PrintPath(2);
bst.PrintPath(4);
bst.PrintPath(6);
bst.PrintPath(8);
bst.PrintPath(9);
cout << "IsBST: " << bst.IsBST() << endl;
return 0;
}
```
输出结果:
```
5->3->2
5->3->4
5->7->6
5->7->8
Node 9 not found!
IsBST: 1
```