返回首页 C++ 模板

二叉搜索树模板

左小右大的二叉树——查找、插入、删除

BST 二叉搜索树 查找 插入 GESP6
#include <bits/stdc++.h>
using namespace std;

struct Node {
    int val;
    Node *left, *right;
    Node(int v) : val(v), left(nullptr), right(nullptr) {}
};

// 查找
Node* search(Node *root, int key) {
    if (!root || root->val == key) return root;
    if (key < root->val) return search(root->left, key);
    return search(root->right, key);
}

// 插入
Node* insert(Node *root, int key) {
    if (!root) return new Node(key);
    if (key < root->val) root->left = insert(root->left, key);
    else if (key > root->val) root->right = insert(root->right, key);
    return root;
}

// 中序遍历(得到有序序列)
void inorder(Node *root) {
    if (!root) return;
    inorder(root->left);
    cout << root->val << " ";
    inorder(root->right);
}

int main() {
    Node *root = nullptr;
    int a[] = {5, 3, 7, 1, 4, 6, 8};
    for (int x : a) root = insert(root, x);
    inorder(root);  // 1 3 4 5 6 7 8
    return 0;
}

📖 要点说明

⚠️ 常见错误