二叉搜索树C++的简单实现

#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);
        }
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值