codes
codes
recovering bst
/*
This code simulates recovering a BST by recovering its in-order traversal array.
In a correct BST, an in-order traversal yields a sorted array.
If two nodes are swapped, the array will have one or two inversions.
This program identifies those inversions and swaps the elements back.
*/
public class RecoverBST {
// Function to recover the "BST" represented as a sorted array with two swap
ped elements.
public static void recover(int[] arr) {
int n = arr.length;
int first = -1, second = -1;
// Scan the array to find the first and possibly the second inversion.
for (int i = 0; i < n - 1; i++) {
if (arr[i] > arr[i + 1]) {
// For the first inversion, mark the first element as 'first' and the next el
ement as 'second'.
if (first == -1) {
first = i;
second = i + 1;
} else {
// For a later inversion, update 'second'.
second = i + 1;
break;
}
}
}
CODES: 1
if (first != -1 && second != -1) {
int temp = arr[first];
arr[first] = arr[second];
arr[second] = temp;
}
}
System.out.println("Before recovery:");
printArray(bstInOrder);
recover(bstInOrder);
System.out.println("After recovery:");
printArray(bstInOrder);
}
BOUNDARY TRAVERSAL:
CODES: 2
// Node class for binary tree
static class Node {
int data;
Node left, right;
Node(int data) {
this.data = data;
left = right = null;
}
}
CODES: 3
}
}
CODES: 4
// Main method to test the boundary traversal.
public static void main(String[] args) {
BoundaryTraversal bt = new BoundaryTraversal();
VIEWS OF TREE:
import java.util.*;
public class TreeViews {
CODES: 5
int data;
Node left, right;
Node(int data) {
this.data = data;
left = right = null;
}
}
CODES: 6
if (node == null) return;
// If this is the first node of its level (traversing right first), print it.
if (maxLevel[0] < level) {
System.out.print(node.data + " ");
maxLevel[0] = level;
}
rightViewUtil(node.right, level + 1, maxLevel);
rightViewUtil(node.left, level + 1, maxLevel);
}
while (!queue.isEmpty()) {
QueueObj temp = queue.poll();
int hd = temp.hd;
// For top view, we add the first node encountered at a horizontal distanc
e.
if (!topViewMap.containsKey(hd)) {
topViewMap.put(hd, temp.node.data);
}
if (temp.node.left != null) {
queue.add(new QueueObj(temp.node.left, hd - 1));
}
if (temp.node.right != null) {
queue.add(new QueueObj(temp.node.right, hd + 1));
}
}
CODES: 7
System.out.print(val + " ");
}
System.out.println();
}
while (!queue.isEmpty()) {
QueueObj temp = queue.poll();
int hd = temp.hd;
// For bottom view, update the map entry at each horizontal distance.
bottomViewMap.put(hd, temp.node.data);
if (temp.node.left != null) {
queue.add(new QueueObj(temp.node.left, hd - 1));
}
if (temp.node.right != null) {
queue.add(new QueueObj(temp.node.right, hd + 1));
}
}
CODES: 8
root.
static class QueueObj {
Node node;
int hd;
QueueObj(Node node, int hd) {
this.node = node;
this.hd = hd;
}
}
1
/ \\
2 3
/ \\ / \\
4 56 7
*/
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
CODES: 9
printTopView(root);
BFS , DFS
import java.util.*;
public class GraphTraversal {
private int V; // Number of vertices
private LinkedList<Integer>[] adj; // Adjacency lists
CODES: 10
visited[s] = true;
queue.add(s);
while (!queue.isEmpty()) {
int vertex = queue.poll();
System.out.print(vertex + " ");
CODES: 11
GraphTraversal graph = new GraphTraversal(4);
DIAL’S ALGO
import java.util.*;
class Node {
int vertex;
int weight;
CODES: 12
this.weight = weight;
}
class Graph {
private int V; // Number of vertices
private List<List<Node>> adj; // Adjacency list
// Find the maximum edge weight (assumes edges have non-negative integ
er weights)
int maxEdgeWeight = 0;
for (int i = 0; i < V; i++) {
for (Node node : adj.get(i)) {
maxEdgeWeight = Math.max(maxEdgeWeight, node.weight);
CODES: 13
}
}
CODES: 14
// Relax edges from u
for (Node edge : adj.get(u)) {
int v = edge.vertex;
int w = edge.weight;
// For demonstration
public static void main(String[] args) {
// Create a graph with 5 vertices (0 to 4)
Graph graph = new Graph(5);
CODES: 15
graph.addEdge(0, 2, 4);
graph.addEdge(1, 2, 1);
graph.addEdge(1, 3, 7);
graph.addEdge(2, 4, 3);
graph.addEdge(3, 4, 1);
BELLMAN FORD:
import java.util.Arrays;
class BellmanFord {
// This class represents a directed edge from 'src' to 'dest' with a given 'weig
ht'.
static class Edge {
int src, dest, weight;
Edge(int src, int dest, int weight) {
this.src = src;
this.dest = dest;
this.weight = weight;
}
}
CODES: 16
V = v;
E = e;
edges = new Edge[e];
}
/**
* Runs Bellman-Ford algorithm from the given 'start' vertex.
*
* If there is a negative cycle reachable from 'start',
* the algorithm will report it.
*/
public void bellmanFord(int start) {
// Step 1: Initialize distances from start to all other vertices
int[] dist = new int[V];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[start] = 0;
CODES: 17
}
// Example usage
public static void main(String[] args) {
int V = 5; // Number of vertices in graph
int E = 8; // Number of edges in graph
/*
* We'll add edges in the form:
* addEdge(index, source, destination, weight)
*
* Example edges:
CODES: 18
* 0 -> 1 (weight -1)
* 0 -> 2 (weight 4)
* 1 -> 2 (weight 3)
* 1 -> 3 (weight 2)
* 1 -> 4 (weight 2)
* 3 -> 2 (weight 5)
* 3 -> 1 (weight 1)
* 4 -> 3 (weight -3)
*/
graph.addEdge(0, 0, 1, -1);
graph.addEdge(1, 0, 2, 4);
graph.addEdge(2, 1, 2, 3);
graph.addEdge(3, 1, 3, 2);
graph.addEdge(4, 1, 4, 2);
graph.addEdge(5, 3, 2, 5);
graph.addEdge(6, 3, 1, 1);
graph.addEdge(7, 4, 3, -3);
binomial heap:
public class BinomialHeap {
private Nodke head; // head of the root list
CODES: 19
// Insert a new key by merging with a single-node heap.
public void insert(int key) {
head = union(head, new Node(key));
}
CODES: 20
Node next = child.sibling;
child.sibling = newHead;
child.parent = null;
newHead = child;
child = next;
}
head = union(head, newHead);
return minNode.key;
}
CODES: 21
// Merges two root lists in order of increasing degree.
private Node merge(Node h1, Node h2) {
if (h1 == null) return h2;
if (h2 == null) return h1;
Node head;
if (h1.degree <= h2.degree) {
head = h1;
h1 = h1.sibling;
} else {
head = h2;
h2 = h2.sibling;
}
Node tail = head;
while (h1 != null && h2 != null) {
if (h1.degree <= h2.degree) {
tail.sibling = h1;
h1 = h1.sibling;
} else {
tail.sibling = h2;
h2 = h2.sibling;
}
tail = tail.sibling;
}
tail.sibling = (h1 != null) ? h1 : h2;
return head;
}
// Simple demonstration.
CODES: 22
public static void main(String[] args) {
BinomialHeap bh = new BinomialHeap();
bh.insert(10);
bh.insert(3);
bh.insert(15);
bh.insert(6);
}
k-ary heap
import java.util.ArrayList;
import java.util.NoSuchElementException;
public class KaryHeap {
private int k; // Number of children per node
private ArrayList<Integer> heap;
CODES: 23
// Returns the index of the j-th child (1-indexed) of the node at index i
private int child(int i, int j) {
return k * i + j;
}
CODES: 24
throw new NoSuchElementException("Heap is empty");
}
int min = heap.get(0);
int last = heap.remove(heap.size() - 1);
if (!heap.isEmpty()) {
heap.set(0, last);
heapifyDown(0);
}
return min;
}
CODES: 25
heap.set(j, temp);
}
// Simple demonstration
public static void main(String[] args) {
// Create a ternary heap (k = 3)
KaryHeap kh = new KaryHeap(3);
kh.insert(10);
kh.insert(4);
kh.insert(15);
kh.insert(2);
kh.insert(7);
winner tree:
/**
* Constructor: Builds a winner tree from the given keys.
* If the number of keys is not a power of 2, the array is padded with Integer.M
AX_VALUE.
*/
public WinnerTree(int[] keys) {
int m = keys.length;
CODES: 26
// Pad the number of leaves to the next power of 2.
n = 1;
while (n < m) {
n *= 2;
}
leaves = new int[n];
for (int i = 0; i < n; i++) {
if (i < m) {
leaves[i] = keys[i];
} else {
leaves[i] = Integer.MAX_VALUE; // Pad with a very high value.
}
}
tree = new int[2 * n]; // Tree indices [n, 2*n-1] will correspond to the leaves.
buildWinnerTree();
}
/**
* Build the winner tree.
* Leaves are stored at positions n to 2*n-1. Internal nodes store the index of t
he winner (the minimum value) from their children.
*/
private void buildWinnerTree() {
// Initialize leaves in the tree.
for (int i = 0; i < n; i++) {
tree[n + i] = i; // Each leaf node holds its own index.
}
// Build the internal nodes from the bottom up.
for (int i = n - 1; i > 0; i--) {
int left = tree[2 * i];
int right = tree[2 * i + 1];
// The winner is the one with the smaller key.
tree[i] = (leaves[left] <= leaves[right]) ? left : right;
}
}
CODES: 27
/**
* Returns the minimum key (the winner) in the tree.
*/
public int getWinner() {
if (n == 0) {
throw new IllegalStateException("The tree is empty.");
}
// The overall winner is stored at tree[1].
return leaves[tree[1]];
}
/**
* Updates the value at a given leaf index and then updates the tree according
ly.
* @param index The index in the original keys array (0-based).
* @param newValue The new value to update.
*/
public void update(int index, int newValue) {
if (index < 0 || index >= n) {
throw new IllegalArgumentException("Index out of range");
}
leaves[index] = newValue;
// Start updating from the corresponding leaf in the tree.
int pos = index + n;
pos /= 2;
while (pos > 0) {
int left = tree[2 * pos];
int right = tree[2 * pos + 1];
tree[pos] = (leaves[left] <= leaves[right]) ? left : right;
pos /= 2;
}
}
/**
* Extracts the winner (minimum value) from the tree.
* For demonstration, the winner's leaf is set to Integer.MAX_VALUE (simulatin
CODES: 28
g removal) and the tree is updated.
*/
public int extractWinner() {
int winnerIndex = tree[1];
int winnerValue = leaves[winnerIndex];
// Simulate removal by setting the leaf to a very high value.
update(winnerIndex, Integer.MAX_VALUE);
return winnerValue;
}
CODES: 29