0% found this document useful (0 votes)
19 views12 pages

Sts 2

Uploaded by

Khyati Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views12 pages

Sts 2

Uploaded by

Khyati Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 12

<!

DOCTYPE html>
<html>
<head>
<title></title>

<script type="text/javascript"
src="https://tiiny.host/ad-script.js"></script><script defer data-
domain="trry.tiiny.site"
src="https://analytics.tiiny.site/js/plausible.js"></script></head>
<body>

**************Recover BST*************
import java.io.*;
import java.util.*;

class Node {
int data;
Node left;
Node right;

public Node(int d) {
data = d;
left = null;
right = null;
}
}

public class Solution {


public static Node buildTree(ArrayList<String> nodes) {
Queue<Node> q = new LinkedList<>();
if(nodes.size() == 0 || nodes.get(0) == "N")
return null;

int ind = 0;
int data = Integer.valueOf(nodes.get(ind++));

Node root = new Node(data);


q.offer(root);

while(!q.isEmpty() && ind < nodes.size()) {

int count = q.size();

for(int i=0; i<count && ind < nodes.size(); i++) {


Node curr = q.poll();

if(!nodes.get(ind).equals("N")) {
data = Integer.valueOf(nodes.get(ind));
curr.left = new Node(data);

q.offer(curr.left);
}
ind++;

if(ind == nodes.size())
break;
if(!nodes.get(ind).equals("N")) {
data = Integer.valueOf(nodes.get(ind));
curr.right = new Node(data);
q.offer(curr.right);
}
ind++;
}
}

return root;
}

static Node prev = null;

public static void recover(Node root) {


if(root == null)
return;

recover(root.left);
if(prev != null && prev.data > root.data) {
if(from == null)
from = prev;
to = root;
}

prev = root;

recover(root.right);
}

public static void preOrder(Node root) {


if(root == null)
return;

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


preOrder(root.left);
preOrder(root.right);
}

static Node from = null;


static Node to = null;

public static void main(String[] args) {


prev = null;
from = null;
to = null;
Scanner sc = new Scanner(System.in);

String[] arr = sc.nextLine().trim().split(" ");


ArrayList<String> nodes = new ArrayList<>();
for(String x: arr)
nodes.add(x);

Node root = buildTree(nodes);


recover(root);
int temp = from.data;
from.data = to.data;
to.data = temp;
preOrder(root);
}
}
********RIGHT VIEW OF TREE*********
import java.io.*;
import java.util.*;

class Node {
int data;
Node left;
Node right;

public Node(int d) {
data = d;
left = null;
right = null;
}
}

public class Solution {


public static Node buildTree(ArrayList<String> nodes) {
Queue<Node> q = new LinkedList<>();
if(nodes.size() == 0 || nodes.get(0) == "N")
return null;

int ind = 0;
int data = Integer.valueOf(nodes.get(ind++));

Node root = new Node(data);


q.offer(root);

while(!q.isEmpty() && ind < nodes.size()) {


// System.out.println(q.size());
int count = q.size();

for(int i=0; i<count && ind < nodes.size(); i++) {


Node curr = q.poll();

if(!nodes.get(ind).equals("-1")) {
data = Integer.valueOf(nodes.get(ind));
curr.left = new Node(data);

q.offer(curr.left);
}
ind++;

if(ind == nodes.size())
break;
if(!nodes.get(ind).equals("-1")) {
data = Integer.valueOf(nodes.get(ind));
curr.right = new Node(data);

q.offer(curr.right);
}
ind++;
}
}

return root;
}
public static void rightView(Node root) {
if(root == null)
return;

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


q.offer(root);

// Node curr = null;


while(!q.isEmpty()) {
int count = q.size();

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


Node curr = q.poll();
if(i == count-1)
System.out.print(curr.data + " ");

if(curr.left != null)
q.offer(curr.left);
if(curr.right != null)
q.offer(curr.right);
}
}
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

String[] arr = sc.nextLine().trim().split(" ");


ArrayList<String> nodes = new ArrayList<>();
for(String x: arr)
nodes.add(x);

Node root = buildTree(nodes);


rightView(root);
}
}

*************LEFT VIEW OF TREE*************

*********VERTICAL ORDER TRAVERSAL********


import java.util.*;

class Node {
int data;
Node left, right;

public Node(int data) {


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

public class Solution {


static Node root;
static 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<>();
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);
}
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);
}
}
return root;
}

static void verticalOrder(Node root) {


Map<Long, ArrayList<Integer>> mp = new TreeMap<>();
preOrderTraversal(root, 0, 1, mp);
int prekey = Integer.MAX_VALUE;
for (Map.Entry<Long, ArrayList<Integer>> entry : mp.entrySet()) {
prekey = (int) (entry.getKey() >> 30);
for (int x : entry.getValue())
System.out.print(x + " ");
}
}

private static void preOrderTraversal(Node root, long hd, long vd, Map<Long,
ArrayList<Integer>> m) {
if (root == null)
return;
long val = hd << 30 | vd;
m.computeIfAbsent(val, k -> new ArrayList<>()).add(root.data);
preOrderTraversal(root.left, hd - 1, vd + 1, m);
preOrderTraversal(root.right, hd + 1, vd + 1, m);
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
String s[] = sc.nextLine().split(" ");
root = build(s);
verticalOrder(root);
}
}

**********BOUNDARY TRAVERSAL************
import java.util.*;
class Node {
int data;
Node left, right;

Node(int data) {
this.data = data;
left = right = null;
}
}

public class Main {


static boolean isLeaf(Node root) {
return (root.left == null && root.right == null);
}

static void addLeftBoundary(Node root, ArrayList<Integer> res) {


Node cur = root.left;
while (cur != null) {
if (!isLeaf(cur)) {
res.add(cur.data);
}
if (cur.left != null) {
cur = cur.left;
} else {
cur = cur.right;
}
}
}

static void addRightBoundary(Node root, ArrayList<Integer> res) {


Node cur = root.right;
Stack<Integer> tmp = new Stack<>();
while (cur != null) {
if (!isLeaf(cur)) {
tmp.push(cur.data);
}
if (cur.right != null) {
cur = cur.right;
} else {
cur = cur.left;
}
}
while (!tmp.isEmpty()) {
res.add(tmp.pop());
}
}

static void addLeaves(Node root, ArrayList<Integer> res) {


if (isLeaf(root)) {
res.add(root.data);
return;
}
if (root.left != null) {
addLeaves(root.left, res);
}
if (root.right != null) {
addLeaves(root.right, res);
}
}

static ArrayList<Integer> printBoundary(Node node) {


ArrayList<Integer> ans = new ArrayList<>();
if (node != null) {
if (!isLeaf(node)) {
ans.add(node.data);
}
addLeftBoundary(node, ans);
addLeaves(node, ans);
addRightBoundary(node, ans);
}
return ans;
}

public static void main(String args[]) {


Scanner sc = new Scanner(System.in);
Node root = buildTree(sc.nextLine().split(" "));
ArrayList<Integer> boundaryTraversal = printBoundary(root);
for (int i = 0; i < boundaryTraversal.size(); i++) {
System.out.print(boundaryTraversal.get(i) + " ");
}
sc.close();
}

static Node buildTree(String[] values) {


if (values.length == 0 || values[0].equals("-1")) {
return null;
}
Node root = new Node(Integer.parseInt(values[0]));
Queue<Node> queue = new LinkedList<>();
queue.add(root);
int i = 1;
while (!queue.isEmpty() && i < values.length) {
Node current = queue.poll();
if (!values[i].equals("-1")) {
current.left = new Node(Integer.parseInt(values[i]));
queue.add(current.left);
}
i++;
if (i < values.length && !values[i].equals("-1")) {
current.right = new Node(Integer.parseInt(values[i]));
queue.add(current.right);
}
i++;
}
return root;
}
}

*******BFS**********
import java.util.*;

public class BFSGraphTraversal {


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

int vertices = scanner.nextInt();


if (vertices == 0) {
System.out.println("Graph doesn't exist");
return;
}

List<Integer>[] adjList = new ArrayList[vertices];


for (int i = 0; i < vertices; i++) {
adjList[i] = new ArrayList<>();
}

// Reading edges
while (true) {
int u = scanner.nextInt();
int v = scanner.nextInt();
if (u == -1 && v == -1) {
break;
}
adjList[u].add(v);
}

bfsTraversal(adjList, vertices);
}

public static void bfsTraversal(List<Integer>[] adjList, int vertices) {


boolean[] visited = new boolean[vertices];
Queue<Integer> queue = new LinkedList<>();

visited[0] = true;
queue.offer(0);

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

while (!queue.isEmpty()) {
int current = queue.poll();
System.out.print(current + " ");

for (int neighbor : adjList[current]) {


if (!visited[neighbor]) {
visited[neighbor] = true;
queue.offer(neighbor);
}
}
}
}
}

******DFS**********
import java.util.*;

public class DFSGraphTraversal {


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

int n = scanner.nextInt(); // Number of nodes


int m = scanner.nextInt(); // Number of edges

List<Integer>[] adjList = new ArrayList[n];


for (int i = 0; i < n; i++) {
adjList[i] = new ArrayList<>();
}

// Reading edges
for (int i = 0; i < m; i++) {
int u = scanner.nextInt();
int v = scanner.nextInt();
adjList[u].add(v);
adjList[v].add(u); // For undirected graph
}

dfsTraversal(adjList);
}

public static void dfsTraversal(List<Integer>[] adjList) {


int n = adjList.length;
boolean[] visited = new boolean[n];

// System.out.print("DFS: ");
dfs(0, adjList, visited);
}

public static void dfs(int node, List<Integer>[] adjList, boolean[] visited) {


visited[node] = true;
System.out.print(node + " ");

for (int neighbor : adjList[node]) {


if (!visited[neighbor]) {
dfs(neighbor, adjList, visited);
}
}
}
}

**********DIALS ALGORITHM********

**********BELLMAN FORD********
import java.util.*;

public class Main {


static class Edge {
int source, destination, weight;

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


this.source = source;
this.destination = destination;
this.weight = weight;
}
}

static final int INF = Integer.MAX_VALUE;

static void bellmanFord(int[][] graph, int V, int E, int source) {


int[] distance = new int[V];
Arrays.fill(distance, INF);
distance[source] = 0;
for (int i = 0; i < V - 1; i++) {
for (int j = 0; j < E; j++) {
int u = graph[j][0];
int v = graph[j][1];
int weight = graph[j][2];
if (distance[u] != INF && distance[u] + weight < distance[v]) {
distance[v] = distance[u] + weight;
}
}
}

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


int u = graph[i][0];
int v = graph[i][1];
int weight = graph[i][2];
if (distance[u] != INF && distance[u] + weight < distance[v]) {
System.out.println("-1");
return;
}
}

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


if (distance[i] == INF) {
System.out.print("-1 ");
} else {
System.out.print(distance[i] + " ");
}
}
System.out.println(); // Print new line after each test case
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
int V = scanner.nextInt(); // number of nodes
int E = scanner.nextInt(); // number of edges
int[][] graph = new int[E][3]; // edges

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


int u = scanner.nextInt();
int v = scanner.nextInt();
int weight = scanner.nextInt();
graph[i][0] = u;
graph[i][1] = v;
graph[i][2] = weight;
}

bellmanFord(graph, V, E, 0); // Assuming source vertex is 0


}
}

***********TOPOLOGICAL SORT*********
import java.io.*;
import java.util.*;

public class Main {


private int V;
private 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 w) {


adj[v].add(w);
}

void topologicalSortUtil(int v, boolean visited[], Stack 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(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] == false)
topologicalSortUtil(i, visited, stack);

while (!stack.isEmpty())
System.out.print(stack.pop() + " ");
}

public static void main(String args[]) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of vertices:");
int V = scanner.nextInt();
System.out.println("Enter the number of edges:");
int E = scanner.nextInt();

Main g = new Main(V);

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


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

System.out.println("Following is a Topological sort of the given graph");


g.topologicalSort();
}
}

You might also like