You are on page 1of 35

//Trees - Recover the BST

import java.util.*;

class TreeNode {

int val;

TreeNode left;

TreeNode right;

TreeNode() {}

TreeNode(int val) { this.val = val; }

TreeNode(int val, TreeNode left, TreeNode right) {

this.val = val;

this.left = left;

this.right = right;

class Solution {

TreeNode first;

TreeNode prev;

TreeNode middle;

TreeNode last;

public void inorder(TreeNode node){

if(node == null){

return;

inorder(node.left);
if( prev != null && (node.val < prev.val)){

if(first == null){

first = prev;

middle = node;

else{

last = node;

prev = node;

inorder(node.right);

public void recoverTree(TreeNode root) {

first = middle = last = null;

prev = new TreeNode(Integer.MIN_VALUE);

inorder(root);

if(first != null && last !=null){

int temp = first.val;

first.val = last.val;

last.val = temp;

else if(first != null && middle !=null){

int temp = first.val;

first.val = middle.val;

middle.val = temp;
}

public class Main {

public static TreeNode constructTree(Integer[] nodes, int index) {

if (index >= nodes.length || nodes[index] == null) {

return null;

TreeNode root = new TreeNode(nodes[index]);

root.left = constructTree(nodes, 2 * index + 1);

root.right = constructTree(nodes, 2 * index + 2);

return root;

public static void inorder(TreeNode root) {

if (root == null) {

return;

inorder(root.left);

System.out.print(root.val + " ");

inorder(root.right);

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

String[] nodesStr = scanner.nextLine().split(" ");

Integer[] nodes = new Integer[nodesStr.length];


for (int i = 0; i < nodesStr.length; i++) {

if (!nodesStr[i].equals("N")) {

nodes[i] = Integer.parseInt(nodesStr[i]);

} else {

nodes[i] = null;

TreeNode root = constructTree(nodes, 0);

Solution solution = new Solution();

solution.recoverTree(root);

inorder(root);

scanner.close();

//Right View Of Binary Tree


import java.util.*;

class TreeNode {

int val;

TreeNode left;

TreeNode right;

public TreeNode(int x) {

val = x;

}
public class Main {

public static List<Integer> rightSideView(TreeNode root) {

List<Integer> result = new ArrayList<>();

if (root == null)

return result;

Queue<TreeNode> queue = new LinkedList<>();

queue.add(root);

while (!queue.isEmpty()) {

int size = queue.size();

for (int i = 0; i < size; i++) {

TreeNode node = queue.poll();

if (i == size - 1) {

result.add(node.val);

if (node.left != null) {

queue.offer(node.left);

if (node.right != null) {

queue.offer(node.right);

return result;

public static TreeNode constructTree(String[] tokens) {

if (tokens == null || tokens.length == 0 || tokens[0].equals("-1"))

return null;

TreeNode root = new TreeNode(Integer.parseInt(tokens[0]));

Queue<TreeNode> queue = new LinkedList<>();

queue.offer(root);
for (int i = 1; i < tokens.length; i += 2) {

TreeNode parent = queue.poll();

if (!tokens[i].equals("-1")) {

parent.left = new TreeNode(Integer.parseInt(tokens[i]));

queue.offer(parent.left);

if (i + 1 < tokens.length && !tokens[i + 1].equals("-1")) {

parent.right = new TreeNode(Integer.parseInt(tokens[i + 1]));

queue.offer(parent.right);

return root;

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

String input = scanner.nextLine();

String[] tokens = input.split(" ");

TreeNode root = constructTree(tokens);

List<Integer> rightSideView = rightSideView(root);

for (int val : rightSideView) {

System.out.print(val + " ");

//Trees - Vertical Order traversal


of //Binary Tree
import java.util.*;

class TreeNode {

int val;

TreeNode left;

TreeNode right;

TreeNode(int val) {

this.val = val;

public class Solution {

static class QueueNode {

TreeNode node;

int hd;

QueueNode(TreeNode node, int hd) {

this.node = node;

this.hd = hd;

public List<Integer> verticalTraversal(TreeNode root) {

List<Integer> result = new ArrayList<>();

if (root == null) return result;

TreeMap<Integer, List<Integer>> map = new TreeMap<>();

Queue<QueueNode> queue = new LinkedList<>();

queue.offer(new QueueNode(root, 0));

while (!queue.isEmpty()) {

int size = queue.size();


Map<Integer, List<Integer>> levelMap = new HashMap<>();

for (int i = 0; i < size; i++) {

QueueNode qNode = queue.poll();

TreeNode node = qNode.node;

int hd = qNode.hd;

if (!levelMap.containsKey(hd)) {

levelMap.put(hd, new ArrayList<>());

levelMap.get(hd).add(node.val);

if (node.left != null) {

queue.offer(new QueueNode(node.left, hd - 1));

if (node.right != null) {

queue.offer(new QueueNode(node.right, hd + 1));

for (Map.Entry<Integer, List<Integer>> entry : levelMap.entrySet()) {

int hd = entry.getKey();

List<Integer> nodes = entry.getValue();

if (!map.containsKey(hd)) {

map.put(hd, new ArrayList<>());

map.get(hd).addAll(nodes);

for (List<Integer> list : map.values()) {

result.addAll(list);

}
return result;

public static TreeNode constructTree(String[] values) {

if (values == null || values.length == 0 || values[0].equals("N")) return null;

Queue<TreeNode> queue = new LinkedList<>();

TreeNode root = new TreeNode(Integer.parseInt(values[0]));

queue.add(root);

for (int i = 1; i < values.length; i += 2) {

TreeNode parent = queue.poll();

if (!values[i].equals("N")) {

TreeNode leftChild = new TreeNode(Integer.parseInt(values[i]));

parent.left = leftChild;

queue.add(leftChild);

if (i + 1 < values.length && !values[i + 1].equals("N")) {

TreeNode rightChild = new TreeNode(Integer.parseInt(values[i + 1]));

parent.right = rightChild;

queue.add(rightChild);

return root;

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

String input = scanner.nextLine();

String[] values = input.split(" ");


TreeNode root = constructTree(values);

Solution solution = new Solution();

List<Integer> result = solution.verticalTraversal(root);

for (int val : result) {

System.out.print(val + " ");

//Trees - Boundary Traversal of


Binary //Tree
import java.util.*;

class TreeNode {

int val;

TreeNode left;

TreeNode right;

TreeNode(int val) {

this.val = val;

public class Solution {

public List<Integer> boundaryOfBinaryTree(TreeNode root) {

List<Integer> result = new ArrayList<>();

if (root == null) return result;

result.add(root.val);

addLeftBoundary(root.left, result);

addLeaves(root, result);
addRightBoundary(root.right, result);

return result;

private void addLeftBoundary(TreeNode node, List<Integer> result) {

if (node == null || (node.left == null && node.right == null)) return;

result.add(node.val);

if (node.left != null) {

addLeftBoundary(node.left, result);

} else {

addLeftBoundary(node.right, result);

private void addRightBoundary(TreeNode node, List<Integer> result) {

if (node == null || (node.left == null && node.right == null)) return;

if (node.right != null) {

addRightBoundary(node.right, result);

} else {

addRightBoundary(node.left, result);

result.add(node.val);

private void addLeaves(TreeNode node, List<Integer> result) {

if (node == null) return;

if (node.left == null && node.right == null) {

result.add(node.val);

return;

}
addLeaves(node.left, result);

addLeaves(node.right, result);

public static TreeNode constructTree(String[] values) {

if (values == null || values.length == 0 || values[0].equals("-1")) return null;

Queue<TreeNode> queue = new LinkedList<>();

TreeNode root = new TreeNode(Integer.parseInt(values[0]));

queue.add(root);

int i = 1;

while (!queue.isEmpty() && i < values.length) {

TreeNode parent = queue.poll();

if (!values[i].equals("-1")) {

TreeNode leftChild = new TreeNode(Integer.parseInt(values[i]));

parent.left = leftChild;

queue.add(leftChild);

i++;

if (i < values.length && !values[i].equals("-1")) {

TreeNode rightChild = new TreeNode(Integer.parseInt(values[i]));

parent.right = rightChild;

queue.add(rightChild);

i++;

return root;

}
public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

String input = scanner.nextLine();

String[] values = input.split(" ");

TreeNode root = constructTree(values);

Solution solution = new Solution();

List<Integer> result = solution.boundaryOfBinaryTree(root);

for (int val : result) {

System.out.print(val + " ");

//Graph - BFS
import java.util.*;

public class BFSGraphTraversal {

private int V;

private LinkedList<Integer> adj[];

BFSGraphTraversal(int v) {

V = v;

adj = new LinkedList[v];

for (int i=0; i<v; ++i)

adj[i] = new LinkedList();

void addEdge(int v,int w) {

adj[v].add(w);

void BFS(int s) {
boolean visited[] = new boolean[V];

LinkedList<Integer> queue = new LinkedList<Integer>();

visited[s] = true;

queue.add(s);

while (queue.size() != 0) {

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 scanner = new Scanner(System.in);

int nodes = scanner.nextInt();

if (nodes == 0) {

System.out.println("Graph doesn't exist");

return;

BFSGraphTraversal g = new BFSGraphTraversal(nodes);

int src, dest;

while (true) {

src = scanner.nextInt();

dest = scanner.nextInt();
if (src == -1 && dest == -1)

break;

g.addEdge(src, dest);

System.out.print("BFS : ");

g.BFS(0);

//DFS
import java.util.*;

public class DFS {

int V;

LinkedList<Integer> adj[];

DFS(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 dFSrec(int s, boolean[] visited) {

visited[s] = true;

System.out.print(s + " ");

for (int n : adj[s]) {


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);

System.out.print("Enter the number of vertices: ");

int n = s.nextInt();

DFS graph = new DFS(n);

int v, e;

System.out.println("Enter edges (vertex1 vertex2), enter -1 -1 to stop:");

while (true) {

v = s.nextInt();

e = s.nextInt();

if (v == -1 && e == -1)

break;

graph.addEdges(v, e);

System.out.print("Enter the source vertex for DFS: ");

int S = s.nextInt();

System.out.print("DFS: ");

graph.dFS(S);

//Dials algorithm
import java.util.*;
public class Graph {
static final int INF = Integer.MAX_VALUE;
private int V;
private ArrayList<ArrayList<Tuple>> adj;

public Graph(int v) {
this.V = v;
this.adj = new ArrayList<ArrayList<Tuple>>();
for (int i = 0; i < v; i++)
this.adj.add(new ArrayList<Tuple>());
}

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<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) {
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();
for (int i = 0; i < e; i++) {
int st = s.nextInt();
int en = s.nextInt();
int d = s.nextInt();
g.AddEdge(st, en, d);
}
g.shortestPath(0, V * e);
}
}

//Graphs - Bellman Ford Algorithm


import java.util.*;

public class Main {

static class Edge {

int source, destination, weight;

public Edge(int source, int destination, int weight) {

this.source = source;

this.destination = destination;

this.weight = weight;

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int n = scanner.nextInt();

int m = scanner.nextInt();

List<Edge> edges = new ArrayList<>();

for (int i = 0; i < m; i++) {


int u = scanner.nextInt();

int v = scanner.nextInt();

int w = scanner.nextInt();

edges.add(new Edge(u, v, w));

int src = 0;

int[] distances = bellmanFord(edges, n, src);

for (int i = 0; i < n; i++) {

System.out.print(distances[i] + " ");

static int[] bellmanFord(List<Edge> edges, int n, int src) {

int[] distances = new int[n];

Arrays.fill(distances, Integer.MAX_VALUE);

distances[src] = 0;

for (int i = 0; i < n - 1; i++) {

for (Edge edge : edges) {

int u = edge.source;

int v = edge.destination;

int weight = edge.weight;

if (distances[u] != Integer.MAX_VALUE && distances[u] + weight < distances[v]) {

distances[v] = distances[u] + weight;

for (Edge edge : edges) {

int u = edge.source;

int v = edge.destination;
int weight = edge.weight;

if (distances[u] != Integer.MAX_VALUE && distances[u] + weight < distances[v]) {

Arrays.fill(distances, -1);

break;

return distances;

//Topological sort
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 addEdge(int v, int e) {

adj[v].add(e);

void topologicalSortUtil(int v, boolean visited[], Stack<Integer> stack) {

visited[v] = true;

Integer i;
Iterator<Integer> it = adj[v].iterator();

while (it.hasNext()) {

i = it.next();

if (!visited[i])

topologicalSortUtil(i, visited, stack);

stack.push(new Integer(v));

void topologicalSort() {

Stack<Integer> stack = new Stack<>();

boolean visited[] = new boolean[V];

for (int i = 0; i < V; i++) {

visited[i] = false;

for (int i = 0; i < V; i++) {

if (!visited[i])

topologicalSortUtil(i, visited, stack);

while (!stack.empty())

System.out.print(stack.pop() + " ");

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.addEdge(v, e);

graph.topologicalSort();

//Heaps - Heap Sort


import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int n = scanner.nextInt();

int[] arr = new int[n];

for (int i = 0; i < n; i++) {

arr[i] = scanner.nextInt();

heapSort(arr);

for (int num : arr) {

System.out.print(num + " ");

public static void heapSort(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);

public static void heapify(int[] arr, int n, int i) {

int largest = i;

int left = 2 * i + 1;

int right = 2 * i + 2;

if (left < n && arr[left] > arr[largest]) {

largest = left;

if (right < n && arr[right] > arr[largest]) {

largest = right;

if (largest != i) {

int temp = arr[i];

arr[i] = arr[largest];

arr[largest] = temp;

heapify(arr, n, largest);

//Heap - Binomial Heap


import java.util.*;

class TreeNode {
int val;

TreeNode left;

TreeNode right;

TreeNode(int val) {

this.val = val;

public class Solution {

public List<Integer> rightSideView(TreeNode root) {

List<Integer> result = new ArrayList<>();

if (root == null) return result;

Queue<TreeNode> queue = new LinkedList<>();

queue.add(root);

while (!queue.isEmpty()) {

int size = queue.size();

TreeNode rightmost = null;

for (int i = 0; i < size; i++) {

TreeNode node = queue.poll();

rightmost = node;

if (node.left != null) queue.add(node.left);

if (node.right != null) queue.add(node.right);

result.add(rightmost.val);

return result;

public static TreeNode constructTree(Integer[] nodes) {


if (nodes == null || nodes.length == 0) return null;

TreeNode[] treeNodes = new TreeNode[nodes.length];

for (int i = 0; i < nodes.length; i++) {

if (nodes[i] != null) {

treeNodes[i] = new TreeNode(nodes[i]);

TreeNode root = treeNodes[0];

for (int i = 0; i < nodes.length; i++) {

if (treeNodes[i] != null) {

int leftIndex = 2 * i + 1;

int rightIndex = 2 * i + 2;

if (leftIndex < nodes.length && treeNodes[leftIndex] != null) {

treeNodes[i].left = treeNodes[leftIndex];

if (rightIndex < nodes.length && treeNodes[rightIndex] != null) {

treeNodes[i].right = treeNodes[rightIndex];

return root;

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

String input = scanner.nextLine();

String[] values = input.split(" ");

Integer[] nodes = new Integer[values.length];

for (int i = 0; i < values.length; i++) {

if (!values[i].equals("null")) {

nodes[i] = Integer.parseInt(values[i]);
}

TreeNode root = constructTree(nodes);

Solution solution = new Solution();

List<Integer> result = solution.rightSideView(root);

for (int i = 0; i < result.size(); i++) {

System.out.print(result.get(i)+" ");

//Winner Tree

import java.io.*;

import java.util.*;

public class Solution {

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

String input=sc.nextLine();

String[] arr=input.split(" ");

ArrayList<Integer> arr1=new ArrayList<Integer>();

for(int i=0;i<arr.length;i++){

arr1.add(Integer.parseInt(arr[i]));

Collections.sort(arr1);

System.out.println(arr1.get(1));

//all views(functions)
import java.util.*;

class Node {

int data;

int hd; // Horizontal distance

Node left, right;

Node(int data) {

this.data = data;

left = right = null;

public class Main {

// Right View

void rightView(Node root) {

if (root == null)

return;

Queue<Node> q = new LinkedList<>();

q.add(root);

while (!q.isEmpty()) {

int n = q.size();

for (int i = 0; i < n; i++) {

Node curr = q.poll();

if (i == n - 1) {

System.out.print(curr.data + " ");

if (curr.left != null)

q.add(curr.left);

if (curr.right != null)

q.add(curr.right);

}
// Left View

void leftView(Node root) {

if (root == null)

return;

Queue<Node> queue = new LinkedList<>();

queue.add(root);

while (!queue.isEmpty()) {

int n = queue.size();

for (int i = 1; i <= n; i++) {

Node temp = queue.poll();

if (i == 1)

System.out.print(temp.data + " ");

if (temp.left != null)

queue.add(temp.left);

if (temp.right != null)

queue.add(temp.right);

// Top View

void topView(Node root) {

if (root == null)

return;

Queue<QueueObj> q = new LinkedList<>();

Map<Integer, Integer> map = new HashMap<>();

int min = 0;

int max = 0;

q.add(new QueueObj(root, 0));

while (!q.isEmpty()) {

QueueObj curr = q.poll();

if (!map.containsKey(curr.hd))

map.put(curr.hd, curr.node.data);
if (curr.node.left != null) {

min = Math.min(min, curr.hd - 1);

q.add(new QueueObj(curr.node.left, curr.hd - 1));

if (curr.node.right != null) {

max = Math.max(max, curr.hd + 1);

q.add(new QueueObj(curr.node.right, curr.hd + 1));

for (; min <= max; min++)

System.out.print(map.get(min) + " ");

// Bottom View

void bottomView(Node root) {

if (root == null)

return;

Map<Integer, Integer> map = new TreeMap<>();

Queue<Node> queue = new LinkedList<>();

root.hd = 0;

queue.add(root);

while (!queue.isEmpty()) {

Node temp = queue.poll();

int 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 + " ");

static class QueueObj {

Node node;

int hd;

QueueObj(Node node, int hd) {

this.node = node;

this.hd = hd;

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

Main ob = new Main();

Node root = new Node(1); // Change this with appropriate tree construction

System.out.println("Right View:");

ob.rightView(root);

System.out.println("\nLeft View:");

ob.leftView(root);

System.out.println("\nTop View:");

ob.topView(root);

System.out.println("\nBottom View:");

ob.bottomView(root);

//K-array
import java.util.*;

public class KaryHeap {


private int[] heap;

private int capacity;

private int size;

private int k;

public KaryHeap(int k, int capacity) {

this.k = k;

this.capacity = capacity;

this.heap = new int[capacity];

this.size = 0;

private int parent(int i) {

return (i - 1) / k;

private int child(int i, int j) {

return k * i + j;

public void insert(int key) {

if (size == capacity) {

System.out.println("Heap overflow");

return;

size++;

int i = size - 1;

heap[i] = key;

while (i != 0 && heap[parent(i)] < heap[i]) {

int temp = heap[i];

heap[i] = heap[parent(i)];

heap[parent(i)] = temp;
i = parent(i);

public void maxHeapify(int i) {

int max = i;

for (int j = 1; j <= k; j++) {

int c = child(i, j);

if (c < size && heap[c] > heap[max]) {

max = c;

if (max != i) {

int temp = heap[i];

heap[i] = heap[max];

heap[max] = temp;

maxHeapify(max);

public int extractMax() {

if (size <= 0)

return Integer.MIN_VALUE;

if (size == 1) {

size--;

return heap[0];

int root = heap[0];

heap[0] = heap[size - 1];

size--;

maxHeapify(0);

return root;
}

public void buildHeap(int[] arr) {

if (arr.length > capacity) {

System.out.println("Input array is larger than heap capacity");

return;

size = arr.length;

for (int i = 0; i < size; i++) {

heap[i] = arr[i];

for (int i = (size - 2) / k; i >= 0; i--) {

maxHeapify(i);

public ArrayList<Integer> getHeapList() {

ArrayList<Integer> list = new ArrayList<>();

for (int i = 0; i < size; i++) {

list.add(heap[i]);

return list;

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int n = scanner.nextInt(); // Number of elements in the array

int[] arr = new int[n];

for (int i = 0; i < n; i++) {

arr[i] = scanner.nextInt();

int capacity = scanner.nextInt(); // Capacity of the heap


int k = scanner.nextInt(); // K value for k-ary heap

KaryHeap heap = new KaryHeap(k, capacity);

heap.buildHeap(arr);

System.out.println("Built Heap : ");

ArrayList<Integer> heapList = heap.getHeapList();

for (int i = 0; i < heapList.size(); i++) {

System.out.print(heapList.get(i) + " ");

System.out.println();

System.out.println("Heap after insertion of 3:");

heapList.add(3);

for (int i = 0; i < heapList.size(); i++) {

System.out.print(heapList.get(i) + " ");

System.out.println();

int extractedMax = heap.extractMax();

System.out.println("Extracted max is " + extractedMax);

System.out.println("Heap after extract max:");

heapList.remove(0); // Remove the extracted max

for (int i = 0; i < heapList.size(); i++) {

System.out.print(heapList.get(i) + " ");

scanner.close();

You might also like