#include <stdio.h>
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
#include <stack>
using namespace std;
class Node {
public:
int e; Node * left = NULL, * right; Node (int e): e(e), left(NULL), right(NULL){}
};
class BST {
public:
Node* root;
int size;
// 初始化类
BST(): size(0), root(NULL) { }
// 判断是否为空
bool is_empty(){
return this->size == 0;
}
// 添加节点,返回新节点的根, 给用户用
void add(int e) {
this->root = add(this->root, e);
}
// 添加节点,返回新节点的根
Node* add(Node* node, int e) {
if (node == NULL) {
this->size++;
return new Node(e);
}
Node & n = *node;
if (n.e < e) {
n.left = add(n.left, e);
} else if (n.e > e) {
n.right = add(n.right, e);
}
return node;
}
// 判断存在元素, 给用户用
bool contains(int e) {
return contains(this->root, e);
}
// 判断是否存在元素
bool contains(Node * node, int e) {
if (node == NULL ) return false;
if (node->e == e) return true;
else if (node->e < e) return this->contains(node->left, e);
else return this->contains(node->right, e);
}
// 前序遍历二叉树
void preOrder() {
preOrder(root);
}
// 前序遍历
void preOrder(Node * n) {
if (n == NULL) return;
printf("%d \n", n->e);
preOrder(n->left);
preOrder(n->right);
}
// 非递归的前序遍历
void preOrderNR() {
stack<Node * > s; // 通过栈来实现
if (this->root == NULL) return;
s.push(this->root);
Node * n;
while (!s.empty()) {
n = s.top();
cout << n-> e << endl;
if (n->right != NULL) s.push(n->right);
else if (n->left != NULL) s.push(n->left);
}
}
};
二叉搜索树C++的简单实现
最新推荐文章于 2024-07-17 08:24:33 发布