AntInLoop

AVL Tree (Self-Balancing BST) Code Implementations

Production-ready AVL Tree (Self-Balancing BST) data structure implementations in C++, Python, Java, and JavaScript on AntInLoop.

Study AVL Tree (Self-Balancing BST) Guide ยท Launch Visualizer

CPP Implementation

#include <vector>

// Fenwick Tree or Binary Indexed Tree class
class FenwickTree {
private:
    std::vector<int> BITree; // Vector to store Binary Indexed Tree
public:
    // Constructs a Fenwick Tree with given number of elements with all values initialized
    FenwickTree(int n) : BITree(n + 1, 0) {}

    // Update the element at the given index to new value (index is 1-based index)
    void update(int index, int val) {
        for (; index < BITree.size(); index += index & -index)
            BITree[index] += val;
    }

    // Get the sum of the first 'index' elements (index is 1-based index)
    int getSum(int index) {
        int sum = 0;
        for (; index > 0; index -= index & -index)
            sum += BITree[index];
        return sum;
    }

    // Returns the size of the Fenwick Tree
    int size() {
        return BITree.size() - 1;
    }

    // Checks if the Fenwick Tree is empty or not
    bool isEmpty() {
        return BITree.size() <= 1;
    }
};