Bellmon ford import java.util.Scanner; public class Main { static class CreateGraph { class CreateEdge { int src, dest, weight; CreateEdge(int src, int dest, int weight) { this.src = src; this.dest = dest; this.weight = weight; } } int V, E; CreateEdge edge[]; CreateGraph(int v, int e) { V = v; E = e; edge = new CreateEdge[e]; } void BellmanFord(int src) { int dist[] = new int[V]; for (int i = 0; i < V; ++i) dist[i] = Integer.MAX_VALUE; dist[src] = 0; for (int i = 1; i < V; ++i) { for (int j = 0; j < E; ++j) { int u = edge[j].src; int v = edge[j].dest; int w = edge[j].weight; if (dist[u] != Integer.MAX_VALUE && dist[u] + w < dist[v]) dist[v] = dist[u] + w; } } for (int j = 0; j < E; ++j) { int u = edge[j].src; int v = edge[j].dest; int w = edge[j].weight; if (dist[u] != Integer.MAX_VALUE && dist[u] + w < dist[v]) { System.out.println("Graph contains negative weight cycle"); return; } } printSolution(dist); } void printSolution(int dist[]) { System.out.println("Vertex Distance from Source"); for (int i = 0; i < V; ++i) System.out.println(i + "tt" + dist[i]); } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of vertices: "); int V = scanner.nextInt(); System.out.print("Enter the number of edges: "); int E = scanner.nextInt(); CreateGraph graph = new CreateGraph(V, E); System.out.println("Enter source, destination, and weight for each edge:"); for (int i = 0; i < E; i++) { int src = scanner.nextInt(); int dest = scanner.nextInt(); int weight = scanner.nextInt(); graph.edge[i] = graph.new CreateEdge(src, dest, weight); } System.out.print("Enter the source vertex: "); int sourceVertex = scanner.nextInt(); graph.BellmanFord(sourceVertex); } } OUTPUT Enter the number of vertices: 5 Enter the number of edges: 8 Enter source, destination, and weight for each edge: 0 1 -1 0 2 4 1 2 3 1 3 2 1 4 2 3 2 5 3 1 1 4 3 -3 Enter the source vertex: 0 Vertex Distance from Source 0 0 1 -1 2 2 3 -2 4 1 Belmon ford import java.util.*; class Main { static class Edge { int src, dest, weight; Edge() { src = dest = weight = 0; } } static class Graph { int V, E; Edge[] edge; Graph(int v, int e) { V = v; E = e; edge = new Edge[e]; for (int i = 0; i < e; ++i) edge[i] = new Edge(); } void BellmanFord(Graph graph, int src) { int V = graph.V, E = graph.E; int dist[] = new int[V]; for (int i = 0; i < V; ++i) dist[i] = Integer.MAX_VALUE; dist[src] = 0; for (int i = 1; i < V; ++i) { for (int j = 0; j < E; ++j) { int u = graph.edge[j].src; int v = graph.edge[j].dest; int weight = graph.edge[j].weight; if (dist[u] != Integer.MAX_VALUE && dist[u] + weight < dist[v]) dist[v] = dist[u] + weight; } } for (int j = 0; j < E; ++j) { int u = graph.edge[j].src; int v = graph.edge[j].dest; int weight = graph.edge[j].weight; if (dist[u] != Integer.MAX_VALUE && dist[u] + weight < dist[v]) { System.out.println(-1); return; } } for (int i = 0; i < V; ++i) if (dist[i] != Integer.MAX_VALUE) System.out.print(dist[i] + " "); else System.out.print(-1 + " "); } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int V = sc.nextInt(); int E = sc.nextInt(); Graph graph = new Graph(V, E); for (int i = 0; i < E; i++) { int u = sc.nextInt(); int v = sc.nextInt(); int w = sc.nextInt(); graph.edge[i].src = u; graph.edge[i].dest = v; graph.edge[i].weight = w; } graph.BellmanFord(graph, 0); sc.close(); } } output 5 8 0 1 -1 0 2 4 1 2 3 1 3 2 1 4 2 3 2 5 3 1 1 4 3 -3 BFS import java.util.*; public class Main { int V; LinkedList<Integer> adj[]; Main(int v) { V = v; adj = new LinkedList[v]; for (int i = 0; i < v; i++) { adj[i] = new LinkedList<>(); } } void addEdges(int v, int e) { if (v < V && e < V) { // Check if vertices are within bounds adj[v].add(e); adj[e].add(v); } else { System.out.println("Vertices out of bounds: " + v + ", " + e); } } void BFS(int s) { boolean visited[] = new boolean[V]; Queue<Integer> queue = new LinkedList<>(); visited[s] = true; queue.add(s); while (!queue.isEmpty()) { s = queue.poll(); System.out.print(s + " "); Iterator<Integer> i = adj[s].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) { visited[n] = true; queue.add(n); } } } } public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); Main graph = new Main(n); int v, e; while (true) { v = s.nextInt(); e = s.nextInt(); if (v == -1 && e == -1) { break; } graph.addEdges(v, e); } int S = s.nextInt(); System.out.print("BFS: "); graph.BFS(S); } } OUTPUT 5 0 1 0 2 1 3 2 4 3 4 -1 -1 0 //SOURCE BFS: 0 1 2 3 4 DFS import java.util.*; public class Main { int V; LinkedList<Integer> adj[]; Main(int v) { V = v; adj = new LinkedList[V]; for (int i = 0; i < V; i++) { adj[i] = new LinkedList<>(); } } void addEdges(int v, int e) { adj[v].add(e); adj[e].add(v); } void DFSrec(int s, boolean[] visited) { visited[s] = true; System.out.print(s + " "); Iterator<Integer> i = adj[s].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) DFSrec(n, visited); } } void DFS(int s) { boolean visited[] = new boolean[V]; DFSrec(s, visited); } public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); Main graph = new Main(n); int v, e; while (true) { v = s.nextInt(); e = s.nextInt(); if (v == -1 && e == -1) break; graph.addEdges(v, e); } int S = s.nextInt(); System.out.print("DFS: "); graph.DFS(S); } } OUTPUT 5 0 1 0 2 1 3 2 4 3 4 -1 -1 0 DFS: 0 1 3 4 2 DIAL ALGO import java.util.*; public class Main { static final int INF = Integer.MAX_VALUE; private int V; // No. of vertices // In a weighted graph, we need to store vertex // and weight pair for every edge private ArrayList<ArrayList<Tuple>> adj; public Main(int v) // Constructor { this.V = v; this.adj = new ArrayList<ArrayList<Tuple>>(); for (int i = 0; i < v; i++) this.adj.add(new ArrayList<Tuple>()); } // function to Add an edge to graph // Adds edge between u and v of weight w public void AddEdge(int u, int v, int w) { adj.get(u).add(new Tuple(v, w)); adj.get(v).add(new Tuple(u, w)); } // Prints shortest paths from src to all other vertices. // W is the maximum weight of an edge public void shortestPath(int src, int W) { int[] dist = new int[V]; Arrays.fill(dist, INF); ArrayList<Integer>[] B = new ArrayList[W * V + 1]; for (int i = 0; i < W * V + 1; i++) B[i] = new ArrayList<Integer>(); B[0].add(src); dist[src] = 0; int idx = 0; while (true) { // Go sequentially through buckets till one // non-empty bucket is found while (B[idx].size() == 0 && idx < W * V) idx++; // If all buckets are empty, we are done. if (idx == W * V) break; // Take top vertex from bucket and pop it int u = B[idx].get(0); B[idx].remove(0); // Process all adjacents of extracted vertex 'u' // and update their distances if required. for (Tuple i : adj.get(u)) { int v = i.v; int weight = i.w; int du = dist[u]; int dv = dist[v]; // If there is shorted path to v through u. if (dv > du + weight) { // updating the distance dist[v] = du + weight; dv = dist[v]; // pushing vertex v into updated // distance's bucket B[dv].add(0, v); } } } // Print shortest distances stored in dist[] System.out.println("Vertex Distance from Source"); for (int i = 0; i < V; ++i) System.out.println(i + "tt" + dist[i]); } static class Tuple { int v, w; Tuple(int v, int w) { this.v = v; this.w = w; } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of vertices: "); int V = scanner.nextInt(); Main g = new Main(V); System.out.print("Enter the number of edges: "); int E = scanner.nextInt(); System.out.println("Enter the edges in format (u v w):"); for (int i = 0; i < E; i++) { int u = scanner.nextInt(); int v = scanner.nextInt(); int w = scanner.nextInt(); g.AddEdge(u, v, w); } System.out.print("Enter the maximum weight of an edge: "); int maxWeight = scanner.nextInt(); System.out.print("Enter the source vertex: "); int src = scanner.nextInt(); // maximum weighted edge - 4 g.shortestPath(src, maxWeight); scanner.close(); } } OUTPUT Enter the number of vertices: 9 Enter the number of edges: 14 Enter the edges in format (u v w): 0 1 4 0 7 8 1 2 8 1 7 11 2 3 7 2 8 2 2 5 4 3 4 9 3 5 14 4 5 10 5 6 2 6 7 1 6 8 6 7 8 7 Enter the maximum weight of an edge: 14 Enter the source vertex: 0 Vertex Distance from Source 0 0 1 4 2 12 3 19 4 21 5 11 6 9 7 8 8 14 Heap sort import java.util.Scanner; class HeapSort { public void sort(int arr[]) { int n = arr.length; // Build heap (rearrange array) for (int i = n / 2 - 1; i >= 0; i--) { heapify(arr, n, i); } // One by one extract an element from heap for (int i = n - 1; i > 0; i--) { // Move current root to end int temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; // call max heapify on the reduced heap heapify(arr, i, 0); } } void heapify(int arr[], int n, int i) { int largest = i; // Initialize largest as root int l = 2 * i + 1; // left = 2*i + 1 int r = 2 * i + 2; // right = 2*i + 2 // If left child is larger than root if (l < n && arr[l] > arr[largest]) { largest = l; } // If right child is larger than largest so far if (r < n && arr[r] > arr[largest]) { largest = r; } // If largest is not root if (largest != i) { int swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; // Recursively heapify the affected sub-tree heapify(arr, n, largest); } } void printArray(int arr[]) { int n = arr.length; for (int i = 0; i < n; ++i) { System.out.print(arr[i] + " "); } System.out.println(); } } public class Main { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int arr[] = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } HeapSort ob = new HeapSort(); ob.sort(arr); ob.printArray(arr); } } OUTPUT 4 5 2 3 1 1 2 3 5 Heap sort SHORTEST import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int[] arr=new int[n]; for(int i=0; i<n; i++){ arr[i]=sc.nextInt(); } Arrays.sort(arr); for(int i=0; i<n; i++){ System.out.print(arr[i]+" "); } } } Output: 5 2 4 5 4 2 2 2 4 4 5 TOPOLOGICAL SORT import java.util.*; public class Main { // Function to perform DFS and topological sorting static void topologicalSortUtil(int v, List<List<Integer>> adj, boolean[] visited, Stack<Integer> stack) { // Mark the current node as visited visited[v] = true; // Recur for all adjacent vertices for (int i : adj.get(v)) { if (!visited[i]) topologicalSortUtil(i, adj, visited, stack); } // Push current vertex to stack which stores the // result stack.push(v); } // Function to perform Topological Sort static void topologicalSort(List<List<Integer>> adj) { // Stack to store the result Stack<Integer> stack = new Stack<>(); int V = adj.size(); boolean[] visited = new boolean[V]; // Call the recursive helper function to store // Topological Sort starting from all vertices one // by one for (int i = 0; i < V; i++) { if (!visited[i]) topologicalSortUtil(i, adj, visited, stack); } // Print contents of stack System.out.print( "Topological sorting of the graph: "); while (!stack.isEmpty()) { System.out.print(stack.pop() + " "); } } // Driver code public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Number of nodes System.out.print("Enter the number of nodes: "); int V = scanner.nextInt(); // Edges List<List<Integer>> edges = new ArrayList<>(); System.out.println("Enter edges in format (source destination), type -1 to stop:"); while (true) { int source = scanner.nextInt(); if (source == -1) break; int destination = scanner.nextInt(); edges.add(Arrays.asList(source, destination)); } // Graph represented as an adjacency list List<List<Integer>> adj = new ArrayList<>(V); for (int i = 0; i < V; i++) { adj.add(new ArrayList<>()); } for (List<Integer> i : edges) { adj.get(i.get(0)).add(i.get(1)); } topologicalSort(adj); scanner.close(); } } OUTPUT Enter the number of nodes: 6 Enter edges in format (source destination), type -1 to stop: 5 2 5 0 4 0 4 1 2 3 3 1 -1 Topological sorting of the graph: 5 4 2 3 1 0 WITHOUT -1 TERMINATE import java.util.*; public class Main { // Function to perform DFS and topological sorting static void topologicalSortUtil(int v, List<List<Integer>> adj, boolean[] visited, Stack<Integer> stack) { // Mark the current node as visited visited[v] = true; // Recur for all adjacent vertices for (int i : adj.get(v)) { if (!visited[i]) topologicalSortUtil(i, adj, visited, stack); } // Push current vertex to stack which stores the // result stack.push(v); } // Function to perform Topological Sort static void topologicalSort(List<List<Integer>> adj) { // Stack to store the result Stack<Integer> stack = new Stack<>(); int V = adj.size(); boolean[] visited = new boolean[V]; // Call the recursive helper function to store // Topological Sort starting from all vertices one // by one for (int i = 0; i < V; i++) { if (!visited[i]) topologicalSortUtil(i, adj, visited, stack); } // Print contents of stack System.out.print( "Topological sorting of the graph: "); while (!stack.isEmpty()) { System.out.print(stack.pop() + " "); } } // Driver code public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Number of nodes System.out.print("Enter the number of nodes: "); int V = scanner.nextInt(); // Edges List<List<Integer>> edges = new ArrayList<>(); System.out.println("Enter edges in format (source destination):"); for (int i = 0; i < V; i++) { int source = scanner.nextInt(); int destinati edges.add(Arrays.asList(source, destination)); } // Graph represented as an adjacency list List<List<Integer>> adj = new ArrayList<>(V); for (int i = 0; i < V; i++) { adj.add(new ArrayList<>()); } for (List<Integer> i : edges) { adj.get(i.get(0)).add(i.get(1)); } topologicalSort(adj); scanner.close(); } } OUTPUT Enter the number of nodes: 6 Enter edges in format (source destination): 5 2 5 0 4 0 4 1 2 3 3 1 Topological sorting of the graph: 5 4 2 3 1 0 BINOMIAL HEAP import java.util.Scanner; class BinomialHeapNode { int key, degree; BinomialHeapNode parent; BinomialHeapNode sibling; BinomialHeapNode child; public BinomialHeapNode(int k) { key = k; degree = 0; parent = null; sibling = null; child = null; } public BinomialHeapNode reverse(BinomialHeapNode sibl) { BinomialHeapNode ret; if (sibling != null) ret = sibling.reverse(this); else ret = this; sibling = sibl; return ret; } public BinomialHeapNode findMinNode() { BinomialHeapNode x = this, y = this; int min = x.key; while (x != null) { if (x.key < min) { y = x; min = x.key; } x = x.sibling; } return y; } public BinomialHeapNode findANodeWithKey(int value) { BinomialHeapNode temp = this, node = null; while (temp != null) { if (temp.key == value) { node = temp; break; } if (temp.child == null) temp = temp.sibling; else { node = temp.child.findANodeWithKey(value); if (node == null) temp = temp.sibling; else break; } } return node; } public int getSize() { return (1 + ((child == null) ? 0 : child.getSize()) + ((sibling == null) ? 0 : sibling.getSize())); } } class BinomialHeap { private BinomialHeapNode Nodes; private int size; public BinomialHeap() { Nodes = null; size = 0; } public boolean isEmpty() { return Nodes == null; } public int getSize() { return size; } public void makeEmpty() { Nodes = null; size = 0; } public void insert(int value) { if (value > 0) { BinomialHeapNode temp = new BinomialHeapNode(value); if (Nodes == null) { Nodes = temp; size = 1; } else { unionNodes(temp); size++; } } } private void merge(BinomialHeapNode binHeap) { BinomialHeapNode temp1 = Nodes, temp2 = binHeap; while ((temp1 != null) && (temp2 != null)) { if (temp1.degree == temp2.degree) { BinomialHeapNode tmp = temp2; temp2 = temp2.sibling; tmp.sibling = temp1.sibling; temp1.sibling = tmp; temp1 = tmp.sibling; } else { if (temp1.degree < temp2.degree) { if ((temp1.sibling == null) || (temp1.sibling.degree > temp2.degree)) { BinomialHeapNode tmp = temp2; temp2 = temp2.sibling; tmp.sibling = temp1.sibling; temp1.sibling = tmp; temp1 = tmp.sibling; } else { temp1 = temp1.sibling; } } else { BinomialHeapNode tmp = temp1; temp1 = temp2; temp2 = temp2.sibling; temp1.sibling = tmp; if (tmp == Nodes) { Nodes = temp1; } } } } if (temp1 == null) { temp1 = Nodes; while (temp1.sibling != null) { temp1 = temp1.sibling; } temp1.sibling = temp2; } } private void unionNodes(BinomialHeapNode binHeap) { merge(binHeap); BinomialHeapNode prevTemp = null, temp = Nodes, nextTemp = Nodes.sibling; while (nextTemp != null) { if ((temp.degree != nextTemp.degree) || ((nextTemp.sibling != null) && (nextTemp.sibling.degree == temp.degree))) { prevTemp = temp; temp = nextTemp; } else { if (temp.key <= nextTemp.key) { temp.sibling = nextTemp.sibling; nextTemp.parent = temp; nextTemp.sibling = temp.child; temp.child = nextTemp; temp.degree++; } else { if (prevTemp == null) { Nodes = nextTemp; } else { prevTemp.sibling = nextTemp; } temp.parent = nextTemp; temp.sibling = nextTemp.child; nextTemp.child = temp; nextTemp.degree++; temp = nextTemp; } } nextTemp = temp.sibling; } } public int findMinimum() { return Nodes.findMinNode().key; } public void delete(int value) { if ((Nodes != null) && (Nodes.findANodeWithKey(value) != null)) { decreaseKeyValue(value, Integer.MIN_VALUE); extractMin(); } } public void decreaseKeyValue(int old_value, int new_value) { BinomialHeapNode temp = Nodes.findANodeWithKey(old_value); if (temp == null) return; temp.key = new_value; BinomialHeapNode tempParent = temp.parent; while ((tempParent != null) && (temp.key < tempParent.key)) { int z = temp.key; temp.key = tempParent.key; tempParent.key = z; temp = tempParent; tempParent = tempParent.parent; } } public int extractMin() { if (Nodes == null) return -1; BinomialHeapNode temp = Nodes, prevTemp = null; BinomialHeapNode minNode = Nodes.findMinNode(); while (temp.key != minNode.key) { prevTemp = temp; temp = temp.sibling; } if (prevTemp == null) { Nodes = temp.sibling; } else { prevTemp.sibling = temp.sibling; } temp = temp.child; BinomialHeapNode fakeNode = temp; while (temp != null) { temp.parent = null; temp = temp.sibling; } if ((Nodes == null) && (fakeNode == null)) { size = 0; } else { if ((Nodes == null) && (fakeNode != null)) { Nodes = fakeNode.reverse(null); size = Nodes.getSize(); } else { if ((Nodes != null) && (fakeNode == null)) { size = Nodes.getSize(); } else { unionNodes(fakeNode.reverse(null)); size = Nodes.getSize(); } } } return minNode.key; } public void displayHeap() { System.out.print("nHeap : "); displayHeapHelper(Nodes); System.out.println("n"); } private void displayHeapHelper(BinomialHeapNode r) { if (r != null) { displayHeapHelper(r.child); System.out.print(r.key + " "); displayHeapHelper(r.sibling); } } } public class Main { public static void main(String[] args) { BinomialHeap binHeap = new BinomialHeap(); Scanner scanner = new Scanner(System.in); while (true) { System.out.print("Enter your choice: "); int choice = scanner.nextInt(); switch (choice) { case 1: System.out.print("Enter value to insert: "); int valueToInsert = scanner.nextInt(); binHeap.insert(valueToInsert); break; case 2: System.out.print("Enter value to delete: "); int valueToDelete = scanner.nextInt(); binHeap.delete(valueToDelete); break; case 3: System.out.println("Size of the binomial heap is " + binHeap.getSize()); binHeap.displayHeap(); break; case 4: System.out.println("Exiting..."); scanner.close(); System.exit(0); default: System.out.println("Invalid choice! Please enter a valid option."); } } } } OUTPUT Enter your choice: 1 Enter value to insert: 45 Enter your choice: 3 Size of the binomial heap is 1 Heap : 45 Enter your choice: 4 Exiting... K-ARRY import java.util.ArrayList; import java.util.Scanner; public class Main { private static int n; private static ArrayList<Integer> arl = new ArrayList<Integer>(); public static int getMax() { if (isEmpty()) { return Integer.MIN_VALUE; } return arl.get(0); } public static boolean isEmpty() { return (arl.size() == 0); } public static void insert(int value) { arl.add(value); int childrenIndex = arl.size() - 1; int parentIndex = (childrenIndex - 1) / n; while (parentIndex >= 0 && arl.get(childrenIndex) > arl.get(parentIndex)) { int temp = arl.get(childrenIndex); arl.set(childrenIndex, arl.get(parentIndex)); arl.set(parentIndex, temp); childrenIndex = parentIndex; parentIndex = (childrenIndex - 1) / n; } } public static void removeMax() { arl.set(0, arl.get(arl.size() - 1)); arl.remove(arl.size() - 1); int parentIndex = 0; while (true) { int largestValueIndex = parentIndex; for (int i = n * parentIndex + 1; i <= (n * parentIndex + n) && i < arl.size(); i++) { if (arl.get(largestValueIndex) < arl.get(i)) { largestValueIndex = i; } } if (largestValueIndex == parentIndex) { break; } else { int temp = arl.get(parentIndex); arl.set(parentIndex, arl.get(largestValueIndex)); arl.set(largestValueIndex, temp); parentIndex = largestValueIndex; } } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the value of n: "); n = scanner.nextInt(); System.out.print("Enter the number of elements to insert: "); int numElements = scanner.nextInt(); System.out.println("Enter " + numElements + " elements:"); for (int i = 0; i < numElements; i++) { int value = scanner.nextInt(); insert(value); } System.out.println("Get Top element: " + getMax()); System.out.println("Heap elements: " + arl); removeMax(); System.out.println("The maximum Element in the heap after removal: " + getMax()); scanner.close(); } } OUTPUT Enter the value of n: 3 Enter the number of elements to insert: 5 Enter 5 elements: 10 20 5 15 30 Get Top element: 30 Heap elements: [30, 20, 5, 15, 10] The maximum Element in the heap after removal: 20 WINNER TREE import java.util.Scanner; public class Main { private int[] tree; private int[] players; private int numPlayers; public Main(int[] players) { this.players = players; this.numPlayers = players.length; int treeSize = 2 * numPlayers - 1; this.tree = new int[treeSize]; buildWinnerTree(); } private void buildWinnerTree() { for (int i = numPlayers - 1; i < tree.length; i++) { tree[i] = i - (numPlayers - 1); } for (int i = numPlayers - 2; i >= 0; i--) { tree[i] = players[tree[2 * i + 1]] < players[tree[2 * i + 2]] ? tree[2 * i + 2] : tree[2 * i + 1]; } } public int getWinner() { return players[tree[0]]; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of players: "); int numPlayers = scanner.nextInt(); int[] players = new int[numPlayers]; System.out.println("Enter the scores of each player:"); for (int i = 0; i < numPlayers; i++) { players[i] = scanner.nextInt(); } Main winnerTree = new Main(players); System.out.println("The winner is: " + winnerTree.getWinner()); scanner.close(); } } Enter the number of players: 8 Enter the scores of each player: 3 7 1 9 4 2 8 5 The winner is: 9 WINNER TREE WITH INDEX import java.util.Arrays; import java.util.Scanner; public class Main { public static class WinnerTree { private int[] tree; private int[] players; public WinnerTree(int[] players) { this.players = players; int n = players.length; int treeSize = 1; while (treeSize < n) { treeSize *= 2; } tree = new int[2 * treeSize - 1]; Arrays.fill(tree, -1); for (int i = 0; i < n; i++) { tree[treeSize - 1 + i] = i; } build(0, 0, treeSize - 1); } private void build(int node, int left, int right) { if (left == right) { if (left < players.length) { tree[node] = left; } return; } int mid = (left + right) / 2; build(2 * node + 1, left, mid); build(2 * node + 2, mid + 1, right); if (tree[2 * node + 1] != -1 && (tree[2 * node + 2] == -1 || players[tree[2 * node + 1]] >= players[tree[2 * node + 2]])) { tree[node] = tree[2 * node + 1]; } else { tree[node] = tree[2 * node + 2]; } } public int getWinner() { return tree[0]; } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of players: "); int numPlayers = scanner.nextInt(); int[] players = new int[numPlayers]; System.out.println("Enter the scores of each player:"); for (int i = 0; i < numPlayers; i++) { System.out.print("Player " + (i + 1) + ": "); players[i] = scanner.nextInt(); } scanner.close(); WinnerTree winnerTree = new WinnerTree(players); int winnerIndex = winnerTree.getWinner(); System.out.println("The player with the highest score is at index: " + winnerIndex); System.out.println("The score of the winning player is: " + players[winnerIndex]); } } OUTPUT Enter the number of players: 5 Enter the scores of each player: Player 1: 10 Player 2: 5 Player 3: 8 Player 4: 12 Player 5: 6 The player with the highest score is at index: 3 The score of the winning player is: 12 WINNING TREE WITH LOWEST SCORE import java.util.Arrays; import java.util.*; public class Main { private int[] tree; private int[] players; public Main(int[] players) { this.players = players; int n = players.length; int treeSize = calculateTreeSize(n); tree = new int[2 * treeSize - 1]; Arrays.fill(tree, -1); for (int i = 0; i < n; i++) { tree[treeSize - 1 + i] = i; } buildWinnerTree(0, 0, treeSize - 1); } private int calculateTreeSize(int n) { int treeSize = 1; while (treeSize < n) { treeSize *= 2; } return treeSize; } private void buildWinnerTree(int node, int left, int right) { if (left == right) return; int mid = (left + right) / 2; buildWinnerTree(2 * node + 1, left, mid); buildWinnerTree(2 * node + 2, mid + 1, right); tree[node] = players[tree[2 * node + 1]] <=players[tree[2 * node + 2]] ? tree[2 * node + 1] : tree[2 *node + 2]; } public int getWinnerIndex() { return tree[0]; } public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int[] players = new int[n]; for(int i=0; i<n; i++){ players[i]=sc.nextInt(); } Main winnerTree = new Main(players); int winnerIndex = winnerTree.getWinnerIndex(); int winningScore = players[winnerIndex]; System.out.println("The player with the lowest score is at index: " + winnerIndex); System.out.println("The score of the winning player is: " + winningScore); } } Output 4 1 7 0 5 The player with the lowest score is at index: 2 The score of the winning player is: 0 Right view import java.util.Scanner; class Node { Node left; Node right; int data; } class BinaryTree { int maxLevel; public void rightViewOfTree(Node node, int level) { if (node == null) { return; } if (level >= maxLevel) { System.out.print(node.data + " "); maxLevel++; } rightViewOfTree(node.right, level + 1); rightViewOfTree(node.left, level + 1); } public Node createNewNode(String val) { if (val.equals("null")) { return null; } Node newNode = new Node(); newNode.data = Integer.parseInt(val); newNode.left = null; newNode.right = null; return newNode; } } public class RightView { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); BinaryTree binaryTree = new BinaryTree(); System.out.print("Enter the nodes in the form of [2,3,null,5]: "); String input = scanner.nextLine().trim(); String[] values = input.substring(1, input.length() - 1).split(","); Node root = binaryTree.createNewNode(values[0]); for (int i = 1; i < values.length; i++) { insertNode(root, values[i]); } System.out.println("Right view of the binary tree:"); binaryTree.rightViewOfTree(root, 0); scanner.close(); } public static void insertNode(Node root, String val) { if (val.equals("null") || root == null) { return; } if (root.left == null) { root.left = new Node(); root.left.data = Integer.parseInt(val); } else if (root.right == null) { root.right = new Node(); root.right.data = Integer.parseInt(val); } else { insertNode(root.right, val); } } } Left view import java.util.Scanner; class Node { Node left; Node right; int data; } class BinaryTree { int maxLevel; public void leftViewOfTree(Node node, int level) { if (node == null) { return; } if (level >= maxLevel) { System.out.print(node.data + " "); maxLevel++; } leftViewOfTree(node.left, level + 1); leftViewOfTree(node.right, level + 1); } public Node createNewNode(String val) { if (val.equals("null")) { return null; } Node newNode = new Node(); newNode.data = Integer.parseInt(val); newNode.left = null; newNode.right = null; return newNode; } } public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); BinaryTree binaryTree = new BinaryTree(); System.out.print("Enter the nodes in the form of [2,3,4,nul,5]: "); String input = scanner.nextLine().trim(); String[] values = input.substring(1, input.length() - 1).split(","); Node root = binaryTree.createNewNode(values[0]); for (int i = 1; i < values.length; i++) { insertNode(root, values[i]); } System.out.println("Left view of the binary tree:"); binaryTree.leftViewOfTree(root, 0); scanner.close(); } public static void insertNode(Node root, String val) { if (val.equals("null") || root == null) { return; } if (root.left == null) { root.left = new Node(); root.left.data = Integer.parseInt(val); } else if (root.right == null) { root.right = new Node(); root.right.data = Integer.parseInt(val); } else { insertNode(root.left, val); } } } Bottom view import java.util.*; import java.util.Map.Entry; class Node { int data, hd; Node left, right; public Node(int data) { this.data = data; left = right = null; this.hd = Integer.MAX_VALUE; } } public class Main { static Node root; static Node build(String s) { s = s.substring(1, s.length() - 1); // Removing '[' and ']' String[] arr = s.split(","); if (arr[0].equals("")) return null; Node root = new Node(Integer.parseInt(arr[0])); Queue<Node> q = new LinkedList<Node>(); q.add(root); int i = 1; while (!q.isEmpty() && i < arr.length) { Node curr = q.poll(); if (!arr[i].equals("null") && !arr[i].equals("")) { int h = Integer.parseInt(arr[i]); curr.left = new Node(h); q.add(curr.left); } i++; if (i >= arr.length) break; if (!arr[i].equals("null") && !arr[i].equals("")) { int h = Integer.parseInt(arr[i]); curr.right = new Node(h); q.add(curr.right); } i++; } return root; } static void bottomview(Node root) { if (root == null) return; int hd = 0; Map<Integer, Integer> map = new TreeMap<>(); Queue<Node> queue = new LinkedList<Node>(); root.hd = hd; queue.add(root); while (!queue.isEmpty()) { Node temp = queue.remove(); hd = temp.hd; map.put(hd, temp.data); if (temp.left != null) { temp.left.hd = hd - 1; queue.add(temp.left); } if (temp.right != null) { temp.right.hd = hd + 1; queue.add(temp.right); } } for (int value : map.values()) { System.out.print(value + " "); } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); Main ob = new Main(); String input = sc.nextLine(); root = build(input); ob.bottomview(root); } } Boundary traversal import java.util.*; public class Main { static class TreeNode { int val; TreeNode left, right; TreeNode(int val) { this.val = val; left = null; right = null; } } public static TreeNode buildTree(String input) { input = input.substring(1, input.length() - 1); // Remove '[' and ']' String[] values = input.split(","); if (values.length == 0 || values[0].equals("null")) { return null; } TreeNode root = new TreeNode(Integer.parseInt(values[0])); Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); int index = 1; while (!queue.isEmpty() && index < values.length) { TreeNode curr = queue.poll(); if (!values[index].equals("null")) { curr.left = new TreeNode(Integer.parseInt(values[index])); queue.offer(curr.left); } index++; if (index < values.length && !values[index].equals("null")) { curr.right = new TreeNode(Integer.parseInt(values[index])); queue.offer(curr.right); } index++; } return root; } public static List<List<Integer>> findVertical(TreeNode root) { TreeMap<Integer, List<Integer>> map = new TreeMap<>(); Queue<Tuple> q = new LinkedList<>(); q.offer(new Tuple(root, 0)); while (!q.isEmpty()) { Tuple tuple = q.poll(); TreeNode node = tuple.node; int col = tuple.col; if (!map.containsKey(col)) { map.put(col, new ArrayList<>()); } map.get(col).add(node.val); if (node.left != null) { q.offer(new Tuple(node.left, col - 1)); } if (node.right != null) { q.offer(new Tuple(node.right, col + 1)); } } return new ArrayList<>(map.values()); } static class Tuple { TreeNode node; int col; public Tuple(TreeNode _node, int _col) { node = _node; col = _col; } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the tree values in the format [val1,val2,...]: "); String input = scanner.nextLine().trim(); TreeNode root = buildTree(input); List<List<Integer>> result = findVertical(root); System.out.println("Output: " + result); scanner.close(); } } Enter the tree values in the format [val1,val2,...]: [1,3,null,null,2] Output: [[3], [1, 2]] Vertical order //VERTICAL ORDER import java.util.*; public class Main{ static TreeMap<Integer, LinkedList<Integer>> map= new TreeMap<>(); static class TreeNode { int data; TreeNode left=null,right=null; TreeNode(int d){ data=d; } } static TreeNode buildTrees(String st[]) { if(st[0]=="N" || st.length==0) return null; TreeNode root= new TreeNode(Integer.parseInt(st[0])); Queue<TreeNode> Q=new LinkedList<TreeNode>(); Q.add(root); int i=1; while(!Q.isEmpty() && i<st.length) { TreeNode current_element=Q.poll(); String current_value=st[i]; if(!current_value.equals("N")) { int element=Integer.parseInt(current_value); current_element.left=new TreeNode(element); Q.add(current_element.left); } i++; if(i>=st.length) break; current_value=st[i]; if(!current_value.equals("N")) { int element=Integer.parseInt(current_value); current_element.right=new TreeNode(element); Q.add(current_element.right); } i++; }return root;} static LinkedList<Integer> key=new LinkedList<>(); static void MapOrder(TreeNode crt,int x){ if(crt==null) return; MapOrder(crt.left,x-1); LinkedList<Integer> t= map.get(x); if(t==null){ t= new LinkedList<>(); t.add(crt.data); key.add(x); } else t.add(crt.data); map.put(x,t); MapOrder(crt.right,x+1); } public static void main(String[] args) { Scanner sc=new Scanner(System.in); String st[]=sc.nextLine().split(" "); TreeNode root= buildTrees(st); MapOrder(root,0); key.sort(Comparator.naturalOrder()); while(key.peek()!=null) System.out.println(map.get(key.remove())); } } // ****************Right view:********************** import java.util.Scanner; class Node { Node left; Node right; int data; } class BinaryTree { int maxLevel; public void rightViewOfTree(Node node, int level) { if (node == null) { return; } if (level >= maxLevel) { System.out.print(node.data + " "); maxLevel++; } rightViewOfTree(node.right, level + 1); rightViewOfTree(node.left, level + 1); } public Node createNewNode(int val) { Node newNode = new Node(); newNode.data = val; newNode.left = null; newNode.right = null; return newNode; } } public class RightView { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); BinaryTree binaryTree = new BinaryTree(); System.out.print("Enter the number of nodes: "); int numNodes = scanner.nextInt(); Node root = null; for (int i = 0; i < numNodes; i++) { System.out.print("Enter value for node " + (i + 1) + ": "); int val = scanner.nextInt(); if (i == 0) { root = binaryTree.createNewNode(val); } else { insertNode(root, val); } } System.out.println("Right view of the binary tree:"); binaryTree.rightViewOfTree(root, 0); scanner.close(); } public static void insertNode(Node root, int val) { if (val < root.data) { if (root.left == null) { root.left = new Node(); root.left.data = val; } else { insertNode(root.left, val); } } else { if (root.right == null) { root.right = new Node(); root.right.data = val; } else { insertNode(root.right, val); } } } } // ****************Bottom view:******************** //BOTTOM VIEW import java.util.*; import java.util.Map.Entry; class Node { int data,hd; Node left, right; public Node(int data){ this.data = data; left = right = null; this.hd = Integer. MAX_VALUE; } } public class Main { static Node root; private List<Integer> path1 = new ArrayList<>(); private List<Integer> path2 = new ArrayList<>(); static Node build(String s[]){ if(s[0]=="N"||s.length==0) return null; Node root=new Node(Integer.parseInt(s[0])); Queue<Node> q=new LinkedList<Node>(); q.add(root); int i=1; while(!q.isEmpty() && i<s.length){ Node curr=q.poll(); String cval=s[i]; if(!cval.equals("N")){ int h=Integer.parseInt(cval); curr.left=new Node(h); q.add(curr.left); } i++; if(i >= s.length) break; cval = s[i]; if(!cval.equals("N")){ int h=Integer.parseInt(cval); curr.right=new Node(h); q.add(curr.right); } i++; } return root; } static void bottomview(Node root){ if (root == null) return; int hd = 0; Map<Integer, Integer> map = new TreeMap<>(); Queue<Node> queue = new LinkedList<Node>(); root.hd = hd; queue.add(root); while (!queue.isEmpty()){ Node temp = queue.remove(); hd = temp.hd; map.put(hd, temp.data); if (temp.left != null){ temp.left.hd = hd-1; queue.add(temp.left); } if (temp.right != null) { temp.right.hd = hd+1; queue.add(temp.right); } } Set<Entry<Integer, Integer>> set = map.entrySet(); Iterator<Entry<Integer, Integer>> iterator = set.iterator(); while (iterator.hasNext()){ Map.Entry<Integer, Integer> me = iterator.next(); System.out.print(me.getValue()+" "); } } public static void main(String[] args){ Scanner sc=new Scanner(System.in); int i; Main ob = new Main(); String s[]=sc.nextLine().split(" "); root = build(s); ob.bottomview(root); } } // ***************Recover BST************** import java.util.*; import java.io.*; import java.util.*; class TreeNode { int data; TreeNode right; TreeNode left; TreeNode(int data) { this.data=data; this.left=null; this.right=null; } } public class Main { static TreeNode build(String st[]) { if(st[0]=="N" || st.length==0) return null; TreeNode root= new TreeNode(Integer.parseInt(st[0])); Queue<TreeNode> Q=new LinkedList<TreeNode>(); Q.add(root); int i=1; while(!Q.isEmpty() && i<st.length) { TreeNode current_element=Q.poll(); String current_value=st[i]; if(!current_value.equals("N")) { int element=Integer.parseInt(current_value); current_element.left=new TreeNode(element); Q.add(current_element.left); } i++; if(i>=st.length) break; current_value=st[i]; if(!current_value.equals("N")) { int element=Integer.parseInt(current_value); current_element.right=new TreeNode(element); Q.add(current_element.right); } i++; }return root;} static TreeNode firstNode,secondNode,prevNode; public static void recoverTree(TreeNode root) { if(root==null) return; inorderTraversal(root); if(firstNode != null && secondNode != null){ int temp = secondNode.data; secondNode.data = firstNode.data; firstNode.data = temp; } } private static void inorderTraversal(TreeNode root){ if(root==null) return; inorderTraversal(root.left); if(prevNode != null && root.data < prevNode.data && firstNode == null) { firstNode = prevNode; } if (prevNode != null && root.data < prevNode.data && firstNode != null) { sec } prevNode = root; inorderTraversal(root.right); } public static void inorder(TreeNode temp) { if(temp==null) return; inorder(temp.left); System.out.print(temp.data+" "); inorder(temp.right); } public static void main(String[] args) { Scanner sc= new Scanner(System.in); String st[]=sc.nextLine().split(" "); if(st[0].equals("N")) { System.out.println("0"); return; } TreeNode root=build(st); inorder(root); recoverTree(root); System.out.println("nAfter Recovery"); inorder(root); } } // *************Left View Of Tree:********************* import java.util.Scanner; class Node { Node left; Node right; int data; } class BinaryTree { int maxLevel; public void leftViewOfTree(Node node, int level) { if (node == null) { return; } if (level >= maxLevel) { System.out.print(node.data + " "); maxLevel++; } leftViewOfTree(node.left, level + 1); leftViewOfTree(node.right, level + 1); } public Node createNewNode(int val) { Node newNode = new Node(); newNode.data = val; newNode.left = null; newNode.right = null; return newNode; } } public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); BinaryTree binaryTree = new BinaryTree(); System.out.print("Enter the number of nodes: "); int numNodes = scanner.nextInt(); Node root = null; for (int i = 0; i < numNodes; i++) { System.out.print("Enter value for node " + (i + 1) + ": "); int val = scanner.nextInt(); if (i == 0) { root = binaryTree.createNewNode(val); } else { insertNode(root, val); } } System.out.println("Left view of the binary tree:"); binaryTree.leftViewOfTree(root, 0); scanner.close(); } public static void insertNode(Node root, int val) { if (val < root.data) { if (root.left == null) { root.left = new Node(); root.left.data = val; } else { insertNode(root.left, val); } } else { if (root.right == null) { root.right = new Node(); root.right.data = val; } else { insertNode(root.right, val); } } } }