You are on page 1of 49

RECOVER THE BST

import java.util.*;

class TreeNode {
int val;
TreeNode left;
TreeNode right;

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

public class Main {


TreeNode firstIncorrectNode = null;
TreeNode secondIncorrectNode = null;
TreeNode prevNode = new TreeNode(Integer.MIN_VALUE);

public void recoverTree(TreeNode root) {


// Perform inorder traversal
inorder(root);
// Swap the values of the two incorrectly placed nodes if found
if (firstIncorrectNode != null && secondIncorrectNode != null) {
int temp = firstIncorrectNode.val;
firstIncorrectNode.val = secondIncorrectNode.val;
secondIncorrectNode.val = temp;
}
}
private void inorder(TreeNode node) {
if (node == null) return;
inorder(node.left);
if (firstIncorrectNode == null && prevNode.val >= node.val) {
firstIncorrectNode = prevNode;
}
if (firstIncorrectNode != null && prevNode.val >= node.val) {
secondIncorrectNode = node;
}
prevNode = node;
inorder(node.right);
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of nodes in the tree:");
int n = scanner.nextInt();
TreeNode root = new TreeNode(scanner.nextInt());
for (int i = 1; i < n; i++) {
int val = scanner.nextInt();
insertIntoBST(root, val);
}
Main solution = new Main();
solution.recoverTree(root);
System.out.println("Inorder Traversal of Recovered BST:");
printInorder(root);
}
private static void insertIntoBST(TreeNode root, int val) {
if (val < root.val) {
if (root.left == null) {
root.left = new TreeNode(val);
} else {
insertIntoBST(root.left, val);
}
} else {
if (root.right == null) {
root.right = new TreeNode(val);
} else {
insertIntoBST(root.right, val);
}
}
}

private static void printInorder(TreeNode node) {


if (node == null) return;
printInorder(node.left);
System.out.print(node.val + " ");
printInorder(node.right);
}
}

View of tree
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 {


Node root;
private List<Integer> path1 = new ArrayList<>();
private List<Integer> path2 = new ArrayList<>();

Node build(String s[]) {


if (s[0].equals("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;
}

// 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.peek();
q.remove();
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;
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 (Map.Entry<Integer, Integer> me : map.entrySet()) {
System.out.print(me.getValue() + " ");
}
}

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 main = new Main();
String s[]=sc.nextLine().split(" ");
main.root = main.build(s);

System.out.println("Right View:");
main.rightview(main.root);
System.out.println();

System.out.println("Left View:");
main.leftview(main.root);
System.out.println();

System.out.println("Top View:");
main.topview(main.root);
System.out.println();

System.out.println("Bottom View:");
main.bottomview(main.root);
}
}
Vertical Order Traversal

import java.util.*;
import java.util.AbstractMap.SimpleEntry;

class TreeNode {
int val;
TreeNode left;
TreeNode right;

public TreeNode(int val) {


this.val = val;
left = null;
right = null;
}
}

public class Main {


// Function to perform Vertical Order Traversal of a binary tree
public static List<List<Integer>> verticalOrderTraversal(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}

Map<Integer, List<Integer>> verticalMap = new TreeMap<>();


Queue<SimpleEntry<TreeNode, Integer>> nodeQueue = new LinkedList<>();
nodeQueue.offer(new SimpleEntry<>(root, 0));

while (!nodeQueue.isEmpty()) {
SimpleEntry<TreeNode, Integer> entry = nodeQueue.poll();
TreeNode node = entry.getKey();
int col = entry.getValue();
verticalMap.computeIfAbsent(col, k -> new ArrayList<>()).add(node.val);
if (node.left != null) {
nodeQueue.offer(new SimpleEntry<>(node.left, col - 1));
}
if (node.right != null) {
nodeQueue.offer(new SimpleEntry<>(node.right, col + 1));
}
}

for (List<Integer> values : verticalMap.values()) {


result.add(values);
}
return result;
}

// Function to build tree from level-order input


public static TreeNode buildTree(List<String> nodes) {
if (nodes.isEmpty() || nodes.get(0).equals("null")) {
return null;
}
Queue<TreeNode> queue = new LinkedList<>();
TreeNode root = new TreeNode(Integer.parseInt(nodes.get(0)));
queue.offer(root);
int i = 1;
while (!queue.isEmpty() && i < nodes.size()) {
TreeNode current = queue.poll();
if (!nodes.get(i).equals("null")) {
current.left = new TreeNode(Integer.parseInt(nodes.get(i)));
queue.offer(current.left);
}
i++;
if (i < nodes.size() && !nodes.get(i).equals("null")) {
current.right = new TreeNode(Integer.parseInt(nodes.get(i)));
queue.offer(current.right);
}
i++;
}
return root;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter level order traversal of the tree (use 'null' for missing
nodes):");
String input = scanner.nextLine();
String[] parts = input.split("\\s+");
List<String> treeNodes = Arrays.asList(parts);
TreeNode root = buildTree(treeNodes);

List<List<Integer>> verticalOrderResult = verticalOrderTraversal(root);

// Printing the Vertical Order Traversal result


System.out.println("Vertical Order Traversal:");
for (List<Integer> column : verticalOrderResult) {
for (int val : column) {
System.out.print(val + " ");
}
System.out.println();
}
}
}

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);
}
static Node insert(Node root, int data) {
if (root == null)
root = new Node(data);
else if (root.data < data)
root.right = insert(root.right, data);
else
root.left = insert(root.left, data);
return root;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
while(input >= 0) {
root = insert(root, input);
input = sc.nextInt();
}
printBoundary(root);
} }

BFS
import java.util.*;

public class BFS {


int V;
LinkedList<Integer> adj[];

BFS(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 bFS(int s) {
boolean visited[] = new boolean[V];
Queue<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] == false) {
visited[n] = true;
queue.add(n);
}
}
}
}

public static void main(String[] args) {


Scanner s = new Scanner(System.in);
int n = s.nextInt();
BFS graph = new BFS(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);
}
}

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

Iterator<Integer> 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 Algorithm

import java.util.*;

class Graph {
private int V;
private List<List<Node>> adj;

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

public void addEdge(int source, int destination, int weight) {


Node node = new Node(destination, weight);
adj.get(source).add(node);
}

public void dijkstra(int startVertex) {


int[] distance = new int[V];
Arrays.fill(distance, Integer.MAX_VALUE);
distance[startVertex] = 0;
PriorityQueue<Node> pq = new PriorityQueue<>(V, Comparator.comparingInt(node ->
node.weight));
pq.add(new Node(startVertex, 0));

while (!pq.isEmpty()) {
int currentVertex = pq.poll().vertex;
for (Node neighbor : adj.get(currentVertex)) {
int newDist = distance[currentVertex] + neighbor.weight;
if (newDist < distance[neighbor.vertex]) {
distance[neighbor.vertex] = newDist;
pq.add(new Node(neighbor.vertex, newDist));
}
}
}

// Print the distances


System.out.println("Vertex\tDistance from Source");
for (int i = 0; i < V; i++) {
System.out.println(i + "\t" + distance[i]);
}
}

static class Node {


int vertex;
int weight;

public Node(int vertex, int weight) {


this.vertex = vertex;
this.weight = weight;
}
}
}

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of vertices:");
int V = scanner.nextInt();
Graph graph = new Graph(V);
System.out.println("Enter the number of edges:");
int E = scanner.nextInt();

System.out.println("Enter the edges in the format <source> <destination> <weight>:");


for (int i = 0; i < E; i++) {
int source = scanner.nextInt();
int destination = scanner.nextInt();
int weight = scanner.nextInt();
graph.addEdge(source, destination, weight);
}

System.out.println("Enter the source vertex for Dijkstra's algorithm:");


int source = scanner.nextInt();
graph.dijkstra(source);
}
}

Bellman-Ford Algorithm

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()-1;
int v = sc.nextInt()-1;
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<Integer> 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<Integer> stack) {


visited[s] = true;
for (int i : adj[s]) {
if (!visited[i]) {
TopoSortRec(i, visited, stack);
}
}
stack.push(s);
}
void TopoSort() {
Stack<Integer> stack = new Stack<>();
boolean visited[] = new boolean[V];
for (int i = 0; i < V; i++) {
if (!visited[i]) {
TopoSortRec(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();
TopologicalSort graph = new TopologicalSort(n);
int v, e;
int i=0;
while (true) {
v = s.nextInt();
e = s.nextInt();
i++;
graph.addEdges(v, e);
if (i==n)
break;
}

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.*;

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

Winner Tree
import java.util.*;

class Node {
int idx;
Node left, right;
}

public 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<Node> 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);
}
}

K-ARY HEAP

import java.util.Scanner;

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

final int capacity = 100;


int[] arr = new int[capacity];
System.out.println("Enter the number of elements (n):");
int n = scanner.nextInt();

System.out.println("Enter " + n + " elements:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

System.out.println("Enter the value of k for the k-ary heap:");


int k = scanner.nextInt();

buildHeap(arr, n, k);
System.out.println("Built Heap: ");
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
System.out.println();

System.out.println("Enter the element to insert:");


int element = scanner.nextInt();
insert(arr, n, k, element);
n++;
System.out.println("Heap after insertion of " + element + ": ");
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
System.out.println();

System.out.println("Extracted max is " + extractMax(arr, n, k));


n--;
System.out.println("\nHeap after extract max: ");
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}

public static void buildHeap(int[] arr, int n, int k) {


for (int i = (n - 1) / k; i >= 0; i--)
restoreDown(arr, n, i, k);
}

public static void insert(int[] arr, int n, int k, int elem) {


arr[n] = elem; // Adjusted to insert at n, the next available position
restoreUp(arr, n, k);
}

public static int extractMax(int[] arr, int n, int k) {


int max = arr[0];
arr[0] = arr[n - 1];
restoreDown(arr, n - 1, 0, k);
return max;
}

public static void restoreDown(int[] arr, int len, int index, int k) {
int[] child = new int[k + 1];
while (true) {
for (int i = 1; i <= k; i++)
child[i] = (k * index + i) < len ? (k * index + i) : -1;
int maxChild = -1, maxChildIndex = -1;
for (int i = 1; i <= k; i++) {
if (child[i] != -1 && arr[child[i]] > maxChild) {
maxChildIndex = child[i];
maxChild = arr[child[i]];
}
}
if (maxChild == -1)
break;
if (arr[index] < arr[maxChildIndex])
swap(arr, index, maxChildIndex);
index = maxChildIndex;
}
}

public static void restoreUp(int[] arr, int index, int k) {


int parent = (index - 1) / k;
while (parent >= 0) {
if (arr[index] > arr[parent]) {
swap(arr, index, parent);
index = parent;
parent = (index - 1) / k;
} else
break;
}
}

public static void swap(int[] arr, int i, int j) {


int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}

HORIZONTAL VIEW

import java.util.*;

class TreeNode {
char val;
TreeNode left;
TreeNode right;

public TreeNode(char val) {


this.val = val;
left = null;
right = null;
}
}

public class Main {


// Function to obtain the Horizontal View of a binary tree
public static List<Character> horizontalView(TreeNode root) {
List<Character> horizontalView = new ArrayList<>();
if (root == null) {
return horizontalView;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int levelSize = queue.size();
for (int i = 0; i < levelSize; i++) {
TreeNode node = queue.poll();
horizontalView.add(node.val);
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
}
return horizontalView;
}
}

WINNER + LOSER

import java.util.Arrays;
import java.util.Scanner;

public class Main {

static class WinnerTree {


private int[] tree;
private int[] players;

public WinnerTree(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;
}
build(0, 0, treeSize - 1);
}
private void build(int node, int left, int right) {
if (left == right) return;
int mid = (left + right) / 2;
build(2 * node + 1, left, mid);
build(2 * node + 2, mid + 1, right);
int leftIndex = tree[2 * node + 1];
int rightIndex = tree[2 * node + 2];
if (leftIndex == -1) {
tree[node] = rightIndex;
} else if (rightIndex == -1) {
tree[node] = leftIndex;
} else {
tree[node] = players[leftIndex] <= players[rightIndex] ? leftIndex : rightIndex;
}
}

public int getWinner() {


return tree[0] != -1 ? players[tree[0]] : -1;
}

private int calculateTreeSize(int n) {


int treeSize = 1;
while (treeSize < n) {
treeSize *= 2;
}
return treeSize;
}
}
static class MinWinnerTree {
private int[] tree;
private int[] players;

public MinWinnerTree(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 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);
int leftIndex = tree[2 * node + 1];
int rightIndex = tree[2 * node + 2];
if (leftIndex == -1) {
tree[node] = rightIndex;
} else if (rightIndex == -1) {
tree[node] = leftIndex;
} else {
tree[node] = players[leftIndex] > players[rightIndex] ? leftIndex : rightIndex;
}
}

public int getWinnerIndex() {


return tree[0] != -1 ? tree[0] : -1;
}

private int calculateTreeSize(int n) {


int treeSize = 1;
while (treeSize < n) {
treeSize *= 2;
}
return treeSize;
}
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of players:");
int n = sc.nextInt();
int[] players = new int[n];
System.out.println("Enter the scores of each player:");
for (int i = 0; i < n; i++) {
players[i] = sc.nextInt();
}

WinnerTree winnerTree = new WinnerTree(players);


System.out.println("The score of the player with the lowest score is: " +
winnerTree.getWinner());
MinWinnerTree minWinnerTree = new MinWinnerTree(players);
int minWinnerIndex = minWinnerTree.getWinnerIndex();
System.out.println("The player with the highest score is at index: " + minWinnerIndex +
" with score: " + players[minWinnerIndex]);
}
}

You might also like