Codes to remember CICS 210 Data Structures


import java.util.Set;          // Allows us to use Sets.
import java.util.HashSet;      // Allows us to create HashSets.
import java.util.Map;          // Allows us to use Maps.
import java.util.HashMap;      // Allows us to create HashMaps.
import java.util.List;         // Allows us to use Lists.
import java.util.LinkedList;   // Allows us to create LinkedLists;


// ============================================================
// PART 1: NODE CLASS
// BUILDING BLOCK FOR ALL TREE METHODS
// ============================================================

class Node<E> {                 // Creates a Node class. E represents the data type.

    E data;                     // Stores the value inside the node.
    Node<E> left;               // Stores a reference to the left child.
    Node<E> right;              // Stores a reference to the right child.

    public Node(E e) {          // Constructor: runs when a new Node is created.
        data = e;               // Saves e inside the node.
    }
}


// ============================================================
// PART 2: SET METHODS
// ============================================================


// 1. UNION
// GOAL: Return a NEW Set containing everything from BOTH Sets.
// Example: {1, 2, 3} and {3, 4, 5} -> {1, 2, 3, 4, 5}

public static <E> Set<E> union(Set<E> s, Set<E> t) { // Receives two Sets and returns their combination.

    Set<E> result = new HashSet<>(s); // Creates a new Set and copies everything from s.

    result.addAll(t);                 // Adds everything from t. Duplicates are ignored.

    return result;                    // Returns the combined Set.
}

// NOTE: Your SI union and Quiz 3 union are EXACTLY THE SAME.
// Learn this method only once.


// 2. INTERSECTION
// GOAL: Return a NEW Set containing only values in BOTH Sets.
// Example: {1, 2, 3} and {3, 4, 5} -> {3}

public static <E> Set<E> intersection(Set<E> s, Set<E> t) { // Receives two Sets and returns their shared values.

    Set<E> result = new HashSet<>(); // Creates a new empty Set.

    result.addAll(s);                // Copies everything from s into result.

    result.retainAll(t);             // Removes anything that is NOT also in t.

    return result;                   // Returns only the shared values.
}


// ============================================================
// PART 3: MAP METHODS
// ============================================================


// 3. ADD TO A MAP OF SETS
// GOAL: Add value v to the Set belonging to key k.
// If the key does not exist, create an empty Set first.

public static <K, V> void addToSet(Map<K, Set<V>> m, K k, V v) { // Receives a Map, key, and value.

    if (!m.containsKey(k)) {       // Checks whether the key does NOT exist.

        m.put(k, new HashSet<V>()); // If missing, creates an empty Set for that key.
    }

    m.get(k).add(v);               // Gets the Set for k and adds v to it.
}

// NOTE: Your SI add(Map<K, Set<V>>) and Quiz 3 add(Map<K, Set<V>>)
// do EXACTLY THE SAME THING.


// 4. ADD TO A MAP OF LISTS
// GOAL: Add value v to the List belonging to key k.
// This is similar to the Map of Sets, but Lists allow duplicates.

public static <K, V> void addToList(Map<K, List<V>> m, K k, V v) { // Receives a Map, key, and value.

    List<V> lst = m.get(k);        // Gets the List associated with key k.

    if (lst == null) {             // Checks whether there is no List for this key.

        lst = new LinkedList<>();  // Creates a new empty LinkedList.

        m.put(k, lst);             // Stores the new List in the Map.
    }

    lst.add(v);                    // Adds v to the List, whether new or existing.
}


// 5. COUNT OCCURRENCES
// GOAL: Count how many times each element appears in a List.
// Example: [A, B, A, A, B] -> A: 3, B: 2

public static <E> Map<E, Integer> countOccurrences(List<E> list) { // Receives a List and returns a Map of counts.

    Map<E, Integer> counts = new HashMap<>(); // Creates an empty Map to store counts.

    for (E element : list) {                  // Goes through every element in the List.

        counts.put(element, counts.getOrDefault(element, 0) + 1); // Gets its count (or 0), adds 1, and saves it.
    }

    return counts;                            // Returns the completed Map.
}


// ============================================================
// PART 4: TREE SEARCHING
// ============================================================


// 6. BINARY TREE CONTAINS
// GOAL: Check whether a value exists ANYWHERE in a binary tree.
// Returns true or false.
// Searches BOTH sides because this is not necessarily a BST.

public static <E> boolean contains(Node<E> n, E key) { // Receives a node and a value to search for.

    if (n == null) {                // Checks whether the current node is empty.

        return false;               // If empty, the value was not found here.
    }

    if (n.data.equals(key)) {       // Checks whether the current node matches the key.

        return true;                // If they match, the value was found.
    }

    return contains(n.left, key) || contains(n.right, key); // Searches LEFT OR RIGHT. True if either side finds it.
}


// 7. BST FIND
// GOAL: Find and RETURN the Node containing the key.
// Uses BST ordering: smaller goes LEFT, larger goes RIGHT.

public static <E extends Comparable<E>> Node<E> find(Node<E> n, E key) { // Receives a node and key. Returns a Node or null.

    if (n == null) {                     // Checks whether the current node is empty.

        return null;                     // If empty, the key was not found.
    }

    if (key.equals(n.data)) {            // Checks whether the current node matches the key.

        return n;                        // Returns the actual Node because we found it.
    }

    if (key.compareTo(n.data) < 0) {     // Checks whether key is SMALLER than the current node.

        return find(n.left, key);        // If smaller, search LEFT only.
    }

    return find(n.right, key);           // Otherwise, search RIGHT only because the key is greater.
}


// ============================================================
// PART 5: TREE TRAVERSAL
// ============================================================


// 8. POSTORDER
// GOAL: Visit nodes in LEFT -> RIGHT -> ROOT order.
// Example: Left subtree, right subtree, then current node.

public void postOrder(Node<E> root) { // Receives the root of the tree.

    if (root == null) {               // Checks whether the current node is empty.

        return;                       // Stops this recursive call if there is no node.
    }

    postOrder(root.left);             // First, visit the entire left subtree.

    postOrder(root.right);            // Second, visit the entire right subtree.

    System.out.println(root.data);    // Last, print the current node's value.
}


// ============================================================
// PART 6: TREE INSERTION
// ============================================================


// 9. INSERT LESSER
// GOAL: Insert e into a BST when e is smaller than EVERY existing value.
// Keep moving LEFT until there is no left child.

public void insertLesser(E e) {       // Receives the value to insert.

    if (root == null) {               // Checks whether the tree is empty.

        root = new Node<E>(e);        // If empty, make e the root.

    } else {                          // If the tree is not empty:

        Node<E> current = root;       // Start at the root.

        while (current.left != null) { // Keep moving left while a left child exists.

            current = current.left;   // Move one step LEFT.
        }

        current.left = new Node<E>(e); // Attach the new node as the left child.
    }

    size++;                           // Increase the tree size by one.
}


// 10. ADD MINIMUM VALUE
// GOAL: Move down the LEFTMOST path and attach e as a left child.
// Similar to insertLesser, but starts with the Node passed as root.

public static <E> void addMinimumValue(E e, Node<E> root) { // Receives a value and starting node.

    while (root.left != null) {       // Keep going while the current node has a left child.

        root = root.left;             // Move one step LEFT.
    }

    root.left = new Node<>(e);        // Attach the new node as the left child.
}


// 11. ADD LEAST SUCCESSOR / LEAST PRED VARIANT
// GOAL: Start in n's RIGHT subtree, then go LEFT as far as possible.
// Attach e as the left child of the smallest node in that right subtree.

public static <E> void addLeastPred(E e, Node<E> n) { // Receives the value and starting node.

    Node<E> current = n;              // Creates a reference starting at n.

    current = n.right;                // Moves into the RIGHT subtree.

    while (current.left != null) {    // Checks whether a left child exists.

        current = current.left;       // Moves LEFT to find the smallest node in the right subtree.
    }

    current.left = new Node<E>(e);    // Attaches e as the left child of that smallest node.
}

// IMPORTANT:
// insertLesser starts at the tree root and follows the leftmost path.
// addMinimumValue starts at the Node passed into it.
// addLeastPred FIRST moves RIGHT, then follows LEFT.
// They are related, but they are NOT interchangeable.


// ============================================================
// PART 7: BST DELETION
// ============================================================


// 12. SPLICE
// GOAL: once node removed, check if it has a child and if it does have the child and the node's parent connect
// Connect its parent directly to its child.
// This is a helper method. The exact implementation depends on your Node class.

public void splice(Node<E> n) {       // Receives the node that needs to be removed.

    // Find the one child, if one exists.
    Node<E> child;                    // Creates a reference for the child that will replace n.

    if (n.left != null) {             // Checks whether n has a left child.

        child = n.left;               // Uses the left child as the replacement.

    } else {                          // Otherwise:

        child = n.right;              // Uses the right child (or null if there are no children).
    }

    // The actual parent connection must be updated here.
    // If n is the root, update root to child.
    // Otherwise, update the parent's left or right reference to child.
    // This requires a parent reference or a way to find n's parent.
}


// 13. REMOVE FROM BST
// GOAL: Remove a node from a BST.
// If it has 0 or 1 child, use splice.
// If it has 2 children, use the LEAST SUCCESSOR.

public void remove(Node<E> n) {       // Receives the node to remove.

    if (n.left == null || n.right == null) { // Checks whether n has zero or one child.

        splice(n);                    // Removes n by connecting its parent to its only child (or null).

    } else {                          // If n has TWO children:

        Node<E> successor = n.right;  // Start at the RIGHT child.

        while (successor.left != null) { // Keep moving LEFT to find the smallest value in the right subtree.

            successor = successor.left; // Move to the left child.
        }

        n.data = successor.data;      // Copy the successor's value into n.

        // The successor must ALSO be removed from its old location.
        // It has no left child, so it can be removed using splice.
        splice(successor);
    }
}