***********Vertical Order traversal*********** import java.util.*; import java.util.Map.Entry; class Node { int data; Node left, right; public Node(int data) { this.data = data; left = right = null; } } class Main { static Node root; private List path1 = new ArrayList<>(); private List 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 q = new LinkedList(); 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 preOrderTraversal(Node root, long hd, long vd, TreeMap> m) { if (root == null) return; long val = hd << 30 | vd; if (m.get(val) !=null) m.get(val).add(root.data); else { Vector v = new Vector (); v.add(root.data); m.put(val, v); } preOrderTraversal(root.left, hd - 1, vd + 1, m); preOrderTraversal(root.right, hd + 1, vd + 1, m); } void verticalOrder(Node root) { TreeMap> mp = new TreeMap<>(); preOrderTraversal(root, 0, 1, mp); int prekey = Integer.MAX_VALUE; for (Entry> entry : mp.entrySet()) { if (prekey != Integer.MAX_VALUE && (entry.getKey() >> 30) != prekey) System.out.println(); prekey = (int) (entry.getKey() >> 30); for (int x : entry.getValue()) System.out.print(x + " "); } } 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.verticalOrder(root); } } ************************************ **********Boundary Traversal*********** import java.util.*; class Node { int data; Node left, right; Node(int item) { data = item; left = right = null; } } class Main { static Node root; static void printLeaves(Node node) { if (node == null) return; printLeaves(node.left); if (node.left == null && node.right == null) System.out.print(node.data + " "); printLeaves(node.right); } static void printBoundaryLeft(Node node) { if (node == null) return; if (node.left != null) { System.out.print(node.data + " "); printBoundaryLeft(node.left); } else if (node.right != null) { System.out.print(node.data + " "); printBoundaryLeft(node.right); } } static void printBoundaryRight(Node node) { if (node == null) return; if (node.right != null) { printBoundaryRight(node.right); System.out.print(node.data + " "); } else if (node.left != null) { printBoundaryRight(node.left); System.out.print(node.data + " "); } } static void printBoundary(Node node) { if (node == null) return; System.out.print(node.data + " "); printBoundaryLeft(node.left); printLeaves(node.left); printLeaves(node.right); printBoundaryRight(node.right); } public static Node buildTree(ArrayList v, int n){ if(v.size()==0 || v.get(0)==-1) return null; Node root=new Node(v.get(0)); int index=1; Queue q=new LinkedList(); q.add(root); while(index v=new ArrayList<>(); for(int i=0; i adjacencyList[]; BFS(int vertices) { this.vertices = vertices; adjacencyList = new ArrayList[vertices]; for (int i = 0; i < vertices; i++) { adjacencyList[i]=new ArrayList<>(); } } void addEdge(int source, int destination) { adjacencyList[source].add(destination); } void breadthFirstSearch(int source) { boolean visited[] = new boolean[vertices]; Queue queue = new LinkedList<>(); visited[source] = true; queue.add(source); while (!queue.isEmpty()) { int currentVertex = queue.poll(); System.out.print(currentVertex + " "); for (int adjacentVertex : adjacencyList[currentVertex]) { if (!visited[adjacentVertex]) { visited[adjacentVertex] = true; queue.add(adjacentVertex); } } } } public static void main(String[] args) { try (Scanner scanner = new Scanner(System.in)) { int vertices = scanner.nextInt(); BFS graph = new BFS(vertices); int source, destination; while (true) { source = scanner.nextInt(); destination = scanner.nextInt(); if (source == -1 && destination == -1) { break; } graph.addEdge(source, destination); } int sourceVertex = scanner.nextInt(); System.out.print("BFS: "); graph.breadthFirstSearch(sourceVertex); /*7 0 1 0 2 1 3 1 4 2 5 2 6 -1 -1 0 */ } } } *********************** ************DFS******************** import java.util.*; public class DFS { int V; LinkedList adj[]; DFS(int v) { V = v; adj = new LinkedList[v]; for(int i=0;i i = adj[s].listIterator(); while(i.hasNext()) { int n = i.next(); if(visited[n]==false) 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(); DFS graph = new DFS(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); } } ********************************** ***********Dial's Algo*********** import java.util.*; public class Graph { static final int INF = Integer.MAX_VALUE; private int V; private ArrayList> adj; public Graph(int v) { this.V = v; this.adj = new ArrayList>(); for (int i = 0; i < v; i++) this.adj.add(new ArrayList()); } 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)); } public void shortestPath(int src, int W) { int[] dist = new int[V]; Arrays.fill(dist, INF); ArrayList[] B = new ArrayList[W * V + 1]; for (int i = 0; i < W * V + 1; i++) B[i]=new ArrayList(); B[0].add(src); dist[src] = 0; int idx = 0; while (true) { while (B[idx].size() == 0 && idx < W * V) idx++; if (idx==W * V) break; int u=B[idx].get(0); B[idx].remove(0); for (Tuple i : adj.get(u)) { int v=i.v; int weight=i.w; int du=dist[u]; int dv=dist[v]; if (dv> du + weight) { dist[v] = du + weight; dv = dist[v]; B[dv].add(0, v); } } } System.out.println(" Vertex Distance from Source"); for (int i=0; i < V; ++i) System.out.println(i + "\t\t" + 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 s=new Scanner(System.in); int V=s.nextInt(); Graph g=new Graph(V); int e=s.nextInt(); int st, en, d; for (int i=0; i < e; i++) { st=s.nextInt(); en=s.nextInt(); d=s.nextInt(); g.AddEdge(st, en, d); } g.shortestPath(0, e); } } *************************************** ****************************************** ************** Bellman Ford **************** import java.util.*; class Main { class Edge { int src, dest, weight; Edge() { src=dest=weight=0; } }; int V, E; Edge edge[]; Main(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(Main 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(); Main graph=new Main(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); } } ********************************** ***************Topological Sort************************** import java.util.*; public class TopologicalSort { int V; LinkedList adj[]; TopologicalSort(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); } void TopoSortRec(int s, boolean visited[], Stack stack) { } void TopoSort() { Stack stack = new Stack (); boolean visited[] = new boolean[V]; for (int i = 0; i < V; i++) { if (visited[i]=false) { TopoSortRec(i, visited, stack); } } while (stack.empty()==false) System.out.print(stack.pop() + " " ); } public static void main(String[] args) { Scanner s=new Scanner(System.in); int n=s.nextInt(); TopologicalSort graph=new TopologicalSort(n); int v, e; while (true) { v=s.nextInt(); e=s.nextInt(); if (v==-1 && e==-1) break; graph.addEdges(v, e); } graph.TopoSort(); } } *********************************************** *************Heap Sort****************** import java.util.*; public class Main { public static void sort(int arr[]) { int N=arr.length; for (int i=N / 2 - 1; i> = 0; i--) heapify(arr, N, i); for (int i = N - 1; i > 0; i--) { int temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; heapify(arr, i, 0); } } static void heapify(int arr[], int N, int i) { int largest = i; int l = 2 * i + 1; int r = 2 * i + 2; if (l < N && arr[l]> arr[largest]) largest = l; if (r < N && arr[r]> arr[largest]) largest = r; if (largest != i) { int swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; heapify(arr, N, largest); } } public static void main(String args[]) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int arr[] = new int[n]; for (int i = 0; i < n; i++) arr[i]=s.nextInt(); sort(arr); System.out.println("Sorted array is"); for (int i=0; i < n; i++) System.out.print(arr[i] + " " ); System.out.println(); } } *************************************************** ****************Binomial Heap********************* import java.util.*; public class practice { public static void main(String[] args){ PriorityQueue pq = new PriorityQueue <>(); pq.offer(12); pq.offer(2); pq.offer(10); pq.offer(1); pq.offer(5); System.out.println("min element: " + pq.peek()); for(Integer x : pq){ System.out.print(x + " "); } System.out.println(); pq.poll(); pq.poll(); System.out.println("min element: " + pq.peek()); for (Integer x : pq){ System.out.print(x + " "); } } } *************************************** ******************K-Arry Heap************ import java.util.Scanner; import java.util.Arrays; import java.util.NoSuchElementException; class DaryHeap { private int d; private int heapSize; private int[] heap; public DaryHeap(int capacity, int numChild) { heapSize = 0; d = numChild; heap = new int[capacity + 1]; Arrays.fill(heap, -1); } public boolean isEmpty() { return heapSize == 0; } public boolean isFull() { return heapSize == heap.length; } public void clear() { heapSize = 0; } private int parent(int i) { return (i - 1) / d; } private int kthChild(int i, int k) { return d * i + k; } public void insert(int x) { if (isFull()) throw new NoSuchElementException("Overflow Exception"); heap[heapSize++] = x; heapifyUp(heapSize - 1); } public int findMin() { if (isEmpty()) throw new NoSuchElementException("Underflow Exception"); return heap[0]; } public int delete(int ind) { if (isEmpty()) throw new NoSuchElementException("Underflow Exception"); int keyItem = heap[ind]; heap[ind] = heap[heapSize - 1]; heapSize--; heapifyDown(ind); return keyItem; } private void heapifyUp(int childInd) { int tmp = heap[childInd]; while (childInd > 0 && tmp < heap[parent(childInd)]) { heap[childInd]=heap[parent(childInd)]; childInd=parent(childInd); } heap[childInd]=tmp; } private void heapifyDown(int ind) { int child; int tmp=heap[ind]; while (kthChild(ind, 1) < heapSize) { child=minChild(ind); if (heap[child] < tmp) heap[ind]=heap[child]; else break; ind=child; } heap[ind]=tmp; } private int minChild(int ind) { int bestChild=kthChild(ind, 1); int k=2; int pos=kthChild(ind, k); while ((k <=d) && (pos < heapSize)) { if (heap[pos] < heap[bestChild]) bestChild=pos; pos=kthChild(ind, k++); } return bestChild; } public void printHeap() { System.out.print("\nHeap="); for (int i = 0; i < heapSize; i++) System.out.print(heap[i] + " "); System.out.println(); } } public class k_arry { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println(" Enter size and D of D-ary Heap"); DaryHeap dh=new DaryHeap(scan.nextInt(), scan.nextInt()); char ch; do { System.out.println("\nD-ary Heap Operations\n"); System.out.println("1. insert "); System.out.println(" 2. delete"); System.out.println("3. check full"); System.out.println("4. check empty"); System.out.println("5. clear"); boolean chk; int choice=scan.nextInt(); switch (choice) { case 1: try { System.out.println("Enter integer element to insert"); dh.insert(scan.nextInt()); } catch (Exception e) { System.out.println(e.getMessage()); } break; case 2: try { System.out.println("Enter delete position"); dh.delete(scan.nextInt() - 1); } catch (Exception e) { System.out.println(e.getMessage()); } break; case 3: System.out.println("Full status=" + dh.isFull()); break; case 4: System.out.println(" Empty status=" + dh.isEmpty()); break; case 5: dh.clear(); System.out.println(" Heap Cleared\n"); break; default: System.out.println("Wrong Entry \n "); break; } /** Display heap **/ dh.printHeap(); System.out.println(" \nDo you want to continue (Type y or n) \n"); ch=scan.next().charAt(0); } while (ch=='Y' || ch=='y' ); } } ********************************************** *****************Winner Tree******************* import java.util.*; class Node { int idx; Node left, right; } class Main { static Node createNode(int idx) { Node t=new Node(); t.left=t.right=null; t.idx=idx; return t; } static void traverseHeight(Node root, int[] arr, int[] res) { if (root==null || (root.left==null && root.right==null)) return; if (res[0]> arr[root.left.idx] && root.left.idx != root.idx) { res[0] = arr[root.left.idx]; traverseHeight(root.right, arr, res); } else if (res[0] > arr[root.right.idx] && root.right.idx != root.idx) { res[0] = arr[root.right.idx]; traverseHeight(root.left, arr, res); } } static void findSecondMin(int[] arr, int n) { List li = new LinkedList <>(); Node root = null; for (int i = 0; i < n; i +=2) { Node t1=createNode(i); Node t2=null; if (i + 1 < n) { t2=createNode(i + 1); root=(arr[i] < arr[i + 1]) ? createNode(i) : createNode(i + 1); root.left=t1; root.right=t2; li.add(root); } else li.add(t1); } int lsize=li.size(); while (lsize !=1) { int last=(lsize & 1)==1 ? lsize - 2 : lsize - 1; for (int i=0; i < last; i +=2) { Node f1=li.remove(0); Node f2=li.remove(0); root=(arr[f1.idx] < arr[f2.idx]) ? createNode(f1.idx) : createNode(f2.idx); root.left=f1; root.right=f2; li.add(root); } if ((lsize & 1)==1) { li.add(li.get(0)); li.remove(0); } lsize=li.size(); } int[] res={ Integer.MAX_VALUE }; traverseHeight(root, arr, res); System.out.println("Minimum: " + arr[root.idx] + " , Second minimum: " + res[0]); } public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int arr[] = new int[n]; for (int i = 0; i < n; i++) arr[i] = s.nextInt(); findSecondMin(arr, n); } } ******************************************************** ****************Another Binomial Heap********************** import java.util.*; 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, findMinimum() - 1); 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 : "); displayHeap(Nodes); System.out.println("\n"); } private void displayHeap(BinomialHeapNode r) { if (r != null) { displayHeap(r.child); System.out.print(r.key + " "); displayHeap(r.sibling); } } } public class Main { public static void main(String[] args) { BinomialHeap binHeap = new BinomialHeap(); Scanner s = new Scanner(System.in); int n = s.nextInt(); for (int i = 0; i < n; i++) binHeap.insert(s.nextInt()); System.out.println("Size:" + binHeap.getSize()); binHeap.displayHeap(); binHeap.delete(s.nextInt()); System.out.println("Size:" + binHeap.getSize()); binHeap.displayHeap(); System.out.println(binHeap.isEmpty()); binHeap.makeEmpty(); System.out.println(binHeap.isEmpty()); } } *******************************