AntInLoop

Tree Data Structure Code Implementations

Production-ready Tree Data Structure data structure implementations in C++, Python, Java, and JavaScript on AntInLoop.

Study Tree Data Structure Guide ยท Launch Visualizer

CPP Implementation

#include <iostream>
#include <list>

// Adjacency List class definition
class AdjacencyList {
private:
    int V; // Number of vertices
    std::list<int> *adj; // Pointer to array containing adjacency lists
public:
    // Constructor
    AdjacencyList(int V);

    // Method to add an edge to the graph
    void addEdge(int v, int w);

    // Method to remove an edge from the graph
    void removeEdge(int v, int w);

    // Method to print the graph
    void printGraph();
};

// Constructor
AdjacencyList::AdjacencyList(int V) {
    this->V = V;
    adj = new std::list<int>[V];
}

// Method to add an edge to the graph
void AdjacencyList::addEdge(int v, int w) {
    adj[v].push_back(w);
}

// Method to remove an edge from the graph
void AdjacencyList::removeEdge(int v, int w) {
    adj[v].remove(w);
}

// Method to print the graph
void AdjacencyList::printGraph() {
    for (int v = 0; v < V; ++v) {
        std::cout << "\
 Adjacency list of vertex " << v << "\
 head ";
        for (auto x : adj[v])
            std::cout << "-> " << x;
        std::cout << std::endl;
    }
}