mirror of
https://github.com/TheAlgorithms/Java.git
synced 2026-03-13 08:40:43 +08:00
Merge branch 'master' of https://github.com/freitzzz/Java
# Conflicts: # Data Structures/HashMap/HashMap.java # Huffman.java # Misc/FloydTriangle.java # Misc/Huffman.java # Misc/InsertDeleteInArray.java # Misc/RootPrecision.java # Misc/ft.java # Misc/root_precision.java # Others/FloydTriangle.java # Others/Huffman.java # Others/insert_delete_in_array.java # Others/root_precision.java # insert_delete_in_array.java
This commit is contained in:
126
data_structures/Bags/Bag.java
Normal file
126
data_structures/Bags/Bag.java
Normal file
@@ -0,0 +1,126 @@
|
||||
package Bags;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
/**
|
||||
* Collection which does not allow removing elements (only collect and iterate)
|
||||
*
|
||||
* @param <Element> - the generic type of an element in this bag
|
||||
*/
|
||||
public class Bag<Element> implements Iterable<Element> {
|
||||
|
||||
private Node<Element> firstElement; // first element of the bag
|
||||
private int size; // size of bag
|
||||
|
||||
private static class Node<Element> {
|
||||
private Element content;
|
||||
private Node<Element> nextElement;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an empty bag
|
||||
*/
|
||||
public Bag() {
|
||||
firstElement = null;
|
||||
size = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if this bag is empty, false otherwise
|
||||
*/
|
||||
public boolean isEmpty() {
|
||||
return firstElement == null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the number of elements
|
||||
*/
|
||||
public int size() {
|
||||
return size;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param element - the element to add
|
||||
*/
|
||||
public void add(Element element) {
|
||||
Node<Element> oldfirst = firstElement;
|
||||
firstElement = new Node<>();
|
||||
firstElement.content = element;
|
||||
firstElement.nextElement = oldfirst;
|
||||
size++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the bag contains a specific element
|
||||
*
|
||||
* @param element which you want to look for
|
||||
* @return true if bag contains element, otherwise false
|
||||
*/
|
||||
public boolean contains(Element element) {
|
||||
Iterator<Element> iterator = this.iterator();
|
||||
while(iterator.hasNext()) {
|
||||
if (iterator.next().equals(element)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return an iterator that iterates over the elements in this bag in arbitrary order
|
||||
*/
|
||||
public Iterator<Element> iterator() {
|
||||
return new ListIterator<>(firstElement);
|
||||
}
|
||||
|
||||
@SuppressWarnings("hiding")
|
||||
private class ListIterator<Element> implements Iterator<Element> {
|
||||
private Node<Element> currentElement;
|
||||
|
||||
public ListIterator(Node<Element> firstElement) {
|
||||
currentElement = firstElement;
|
||||
}
|
||||
|
||||
public boolean hasNext() {
|
||||
return currentElement != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* remove is not allowed in a bag
|
||||
*/
|
||||
@Override
|
||||
public void remove() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public Element next() {
|
||||
if (!hasNext())
|
||||
throw new NoSuchElementException();
|
||||
Element element = currentElement.content;
|
||||
currentElement = currentElement.nextElement;
|
||||
return element;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* main-method for testing
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
Bag<String> bag = new Bag<>();
|
||||
|
||||
bag.add("1");
|
||||
bag.add("1");
|
||||
bag.add("2");
|
||||
|
||||
System.out.println("size of bag = " + bag.size());
|
||||
for (String s : bag) {
|
||||
System.out.println(s);
|
||||
}
|
||||
|
||||
System.out.println(bag.contains(null));
|
||||
System.out.println(bag.contains("1"));
|
||||
System.out.println(bag.contains("3"));
|
||||
}
|
||||
|
||||
}
|
||||
124
data_structures/Buffers/CircularBuffer.java
Normal file
124
data_structures/Buffers/CircularBuffer.java
Normal file
@@ -0,0 +1,124 @@
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public class CircularBuffer {
|
||||
private char[] _buffer;
|
||||
public final int _buffer_size;
|
||||
private int _write_index = 0;
|
||||
private int _read_index = 0;
|
||||
private AtomicInteger _readable_data = new AtomicInteger(0);
|
||||
|
||||
public CircularBuffer(int buffer_size) {
|
||||
if(!IsPowerOfTwo(buffer_size)) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
this._buffer_size = buffer_size;
|
||||
_buffer = new char[buffer_size];
|
||||
}
|
||||
|
||||
private boolean IsPowerOfTwo(int i) {
|
||||
return (i & (i - 1)) == 0;
|
||||
}
|
||||
|
||||
private int getTrueIndex(int i) {
|
||||
return i % _buffer_size;
|
||||
}
|
||||
|
||||
public Character readOutChar() {
|
||||
Character result = null;
|
||||
|
||||
//if we have data to read
|
||||
if(_readable_data.get() > 0) {
|
||||
result = new Character(_buffer[getTrueIndex(_read_index)]);
|
||||
_readable_data.decrementAndGet();
|
||||
_read_index++;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public boolean writeToCharBuffer(char c) {
|
||||
boolean result = false;
|
||||
|
||||
//if we can write to the buffer
|
||||
if(_readable_data.get() < _buffer_size) {
|
||||
//write to buffer
|
||||
_buffer[getTrueIndex(_write_index)] = c;
|
||||
_readable_data.incrementAndGet();
|
||||
_write_index++;
|
||||
result = true;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static class TestWriteWorker implements Runnable {
|
||||
String _alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
|
||||
Random _random = new Random();
|
||||
CircularBuffer _buffer;
|
||||
public TestWriteWorker(CircularBuffer cb) {
|
||||
this._buffer = cb;
|
||||
}
|
||||
|
||||
private char getRandomChar() {
|
||||
return _alphabet.charAt(_random.nextInt(_alphabet.length()));
|
||||
}
|
||||
|
||||
public void run() {
|
||||
while(!Thread.interrupted()) {
|
||||
if(!_buffer.writeToCharBuffer(getRandomChar())){
|
||||
Thread.yield();
|
||||
try{
|
||||
Thread.sleep(10);
|
||||
} catch (InterruptedException e) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class TestReadWorker implements Runnable {
|
||||
CircularBuffer _buffer;
|
||||
public TestReadWorker(CircularBuffer cb) {
|
||||
this._buffer = cb;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
System.out.println("Printing Buffer:");
|
||||
while(!Thread.interrupted()) {
|
||||
Character c = _buffer.readOutChar();
|
||||
if(c != null) {
|
||||
System.out.print(c.charValue());
|
||||
} else {
|
||||
Thread.yield();
|
||||
try {
|
||||
Thread.sleep(10);
|
||||
} catch (InterruptedException e) {
|
||||
System.out.println();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
int buffer_size = 1024;
|
||||
//create circular buffer
|
||||
CircularBuffer cb = new CircularBuffer(buffer_size);
|
||||
|
||||
//create threads that read and write the buffer.
|
||||
Thread write_thread = new Thread(new TestWriteWorker(cb));
|
||||
Thread read_thread = new Thread(new TestReadWorker(cb));
|
||||
read_thread.start();
|
||||
write_thread.start();
|
||||
|
||||
//wait some amount of time
|
||||
Thread.sleep(10000);
|
||||
|
||||
//interrupt threads and exit
|
||||
write_thread.interrupt();
|
||||
read_thread.interrupt();
|
||||
}
|
||||
}
|
||||
174
data_structures/Graphs/Kruskal's Algorithm.java
Normal file
174
data_structures/Graphs/Kruskal's Algorithm.java
Normal file
@@ -0,0 +1,174 @@
|
||||
// Java program for Kruskal's algorithm to find Minimum Spanning Tree
|
||||
// of a given connected, undirected and weighted graph
|
||||
import java.util.*;
|
||||
import java.lang.*;
|
||||
import java.io.*;
|
||||
|
||||
class Graph
|
||||
{
|
||||
// A class to represent a graph edge
|
||||
class Edge implements Comparable<Edge>
|
||||
{
|
||||
int src, dest, weight;
|
||||
|
||||
// Comparator function used for sorting edges based on
|
||||
// their weight
|
||||
public int compareTo(Edge compareEdge)
|
||||
{
|
||||
return this.weight-compareEdge.weight;
|
||||
}
|
||||
};
|
||||
|
||||
// A class to represent a subset for union-find
|
||||
class subset
|
||||
{
|
||||
int parent, rank;
|
||||
};
|
||||
|
||||
int V, E; // V-> no. of vertices & E->no.of edges
|
||||
Edge edge[]; // collection of all edges
|
||||
|
||||
// Creates a graph with V vertices and E edges
|
||||
Graph(int v, int e)
|
||||
{
|
||||
V = v;
|
||||
E = e;
|
||||
edge = new Edge[E];
|
||||
for (int i=0; i<e; ++i)
|
||||
edge[i] = new Edge();
|
||||
}
|
||||
|
||||
// A utility function to find set of an element i
|
||||
// (uses path compression technique)
|
||||
int find(subset subsets[], int i)
|
||||
{
|
||||
// find root and make root as parent of i (path compression)
|
||||
if (subsets[i].parent != i)
|
||||
subsets[i].parent = find(subsets, subsets[i].parent);
|
||||
|
||||
return subsets[i].parent;
|
||||
}
|
||||
|
||||
// A function that does union of two sets of x and y
|
||||
// (uses union by rank)
|
||||
void Union(subset subsets[], int x, int y)
|
||||
{
|
||||
int xroot = find(subsets, x);
|
||||
int yroot = find(subsets, y);
|
||||
|
||||
// Attach smaller rank tree under root of high rank tree
|
||||
// (Union by Rank)
|
||||
if (subsets[xroot].rank < subsets[yroot].rank)
|
||||
subsets[xroot].parent = yroot;
|
||||
else if (subsets[xroot].rank > subsets[yroot].rank)
|
||||
subsets[yroot].parent = xroot;
|
||||
|
||||
// If ranks are same, then make one as root and increment
|
||||
// its rank by one
|
||||
else
|
||||
{
|
||||
subsets[yroot].parent = xroot;
|
||||
subsets[xroot].rank++;
|
||||
}
|
||||
}
|
||||
|
||||
// The main function to construct MST using Kruskal's algorithm
|
||||
void KruskalMST()
|
||||
{
|
||||
Edge result[] = new Edge[V]; // Tnis will store the resultant MST
|
||||
int e = 0; // An index variable, used for result[]
|
||||
int i = 0; // An index variable, used for sorted edges
|
||||
for (i=0; i<V; ++i)
|
||||
result[i] = new Edge();
|
||||
|
||||
// Step 1: Sort all the edges in non-decreasing order of their
|
||||
// weight. If we are not allowed to change the given graph, we
|
||||
// can create a copy of array of edges
|
||||
Arrays.sort(edge);
|
||||
|
||||
// Allocate memory for creating V ssubsets
|
||||
subset subsets[] = new subset[V];
|
||||
for(i=0; i<V; ++i)
|
||||
subsets[i]=new subset();
|
||||
|
||||
// Create V subsets with single elements
|
||||
for (int v = 0; v < V; ++v)
|
||||
{
|
||||
subsets[v].parent = v;
|
||||
subsets[v].rank = 0;
|
||||
}
|
||||
|
||||
i = 0; // Index used to pick next edge
|
||||
|
||||
// Number of edges to be taken is equal to V-1
|
||||
while (e < V - 1)
|
||||
{
|
||||
// Step 2: Pick the smallest edge. And increment the index
|
||||
// for next iteration
|
||||
Edge next_edge = new Edge();
|
||||
next_edge = edge[i++];
|
||||
|
||||
int x = find(subsets, next_edge.src);
|
||||
int y = find(subsets, next_edge.dest);
|
||||
|
||||
// If including this edge does't cause cycle, include it
|
||||
// in result and increment the index of result for next edge
|
||||
if (x != y)
|
||||
{
|
||||
result[e++] = next_edge;
|
||||
Union(subsets, x, y);
|
||||
}
|
||||
// Else discard the next_edge
|
||||
}
|
||||
|
||||
// print the contents of result[] to display the built MST
|
||||
System.out.println("Following are the edges in the constructed MST");
|
||||
for (i = 0; i < e; ++i)
|
||||
System.out.println(result[i].src+" -- "+result[i].dest+" == "+
|
||||
result[i].weight);
|
||||
}
|
||||
|
||||
// Driver Program
|
||||
public static void main (String[] args)
|
||||
{
|
||||
|
||||
/* Let us create following weighted graph
|
||||
10
|
||||
0--------1
|
||||
| \ |
|
||||
6| 5\ |15
|
||||
| \ |
|
||||
2--------3
|
||||
4 */
|
||||
int V = 4; // Number of vertices in graph
|
||||
int E = 5; // Number of edges in graph
|
||||
Graph graph = new Graph(V, E);
|
||||
|
||||
// add edge 0-1
|
||||
graph.edge[0].src = 0;
|
||||
graph.edge[0].dest = 1;
|
||||
graph.edge[0].weight = 10;
|
||||
|
||||
// add edge 0-2
|
||||
graph.edge[1].src = 0;
|
||||
graph.edge[1].dest = 2;
|
||||
graph.edge[1].weight = 6;
|
||||
|
||||
// add edge 0-3
|
||||
graph.edge[2].src = 0;
|
||||
graph.edge[2].dest = 3;
|
||||
graph.edge[2].weight = 5;
|
||||
|
||||
// add edge 1-3
|
||||
graph.edge[3].src = 1;
|
||||
graph.edge[3].dest = 3;
|
||||
graph.edge[3].weight = 15;
|
||||
|
||||
// add edge 2-3
|
||||
graph.edge[4].src = 2;
|
||||
graph.edge[4].dest = 3;
|
||||
graph.edge[4].weight = 4;
|
||||
|
||||
graph.KruskalMST();
|
||||
}
|
||||
}
|
||||
114
data_structures/Graphs/PrimMST.java
Normal file
114
data_structures/Graphs/PrimMST.java
Normal file
@@ -0,0 +1,114 @@
|
||||
// A Java program for Prim's Minimum Spanning Tree (MST) algorithm.
|
||||
//adjacency matrix representation of the graph
|
||||
|
||||
import java.lang.*;
|
||||
|
||||
class PrimMST
|
||||
{
|
||||
// Number of vertices in the graph
|
||||
private static final int V=5;
|
||||
|
||||
// A utility function to find the vertex with minimum key
|
||||
// value, from the set of vertices not yet included in MST
|
||||
int minKey(int key[], Boolean mstSet[])
|
||||
{
|
||||
// Initialize min value
|
||||
int min = Integer.MAX_VALUE, min_index=-1;
|
||||
|
||||
for (int v = 0; v < V; v++)
|
||||
if (mstSet[v] == false && key[v] < min)
|
||||
{
|
||||
min = key[v];
|
||||
min_index = v;
|
||||
}
|
||||
|
||||
return min_index;
|
||||
}
|
||||
|
||||
// A utility function to print the constructed MST stored in
|
||||
// parent[]
|
||||
void printMST(int parent[], int n, int graph[][])
|
||||
{
|
||||
System.out.println("Edge Weight");
|
||||
for (int i = 1; i < V; i++)
|
||||
System.out.println(parent[i]+" - "+ i+" "+
|
||||
graph[i][parent[i]]);
|
||||
}
|
||||
|
||||
// Function to construct and print MST for a graph represented
|
||||
// using adjacency matrix representation
|
||||
void primMST(int graph[][])
|
||||
{
|
||||
// Array to store constructed MST
|
||||
int parent[] = new int[V];
|
||||
|
||||
// Key values used to pick minimum weight edge in cut
|
||||
int key[] = new int [V];
|
||||
|
||||
// To represent set of vertices not yet included in MST
|
||||
Boolean mstSet[] = new Boolean[V];
|
||||
|
||||
// Initialize all keys as INFINITE
|
||||
for (int i = 0; i < V; i++)
|
||||
{
|
||||
key[i] = Integer.MAX_VALUE;
|
||||
mstSet[i] = false;
|
||||
}
|
||||
|
||||
// Always include first 1st vertex in MST.
|
||||
key[0] = 0; // Make key 0 so that this vertex is
|
||||
// picked as first vertex
|
||||
parent[0] = -1; // First node is always root of MST
|
||||
|
||||
// The MST will have V vertices
|
||||
for (int count = 0; count < V-1; count++)
|
||||
{
|
||||
// Pick thd minimum key vertex from the set of vertices
|
||||
// not yet included in MST
|
||||
int u = minKey(key, mstSet);
|
||||
|
||||
// Add the picked vertex to the MST Set
|
||||
mstSet[u] = true;
|
||||
|
||||
// Update key value and parent index of the adjacent
|
||||
// vertices of the picked vertex. Consider only those
|
||||
// vertices which are not yet included in MST
|
||||
for (int v = 0; v < V; v++)
|
||||
|
||||
// graph[u][v] is non zero only for adjacent vertices of m
|
||||
// mstSet[v] is false for vertices not yet included in MST
|
||||
// Update the key only if graph[u][v] is smaller than key[v]
|
||||
if (graph[u][v]!=0 && mstSet[v] == false &&
|
||||
graph[u][v] < key[v])
|
||||
{
|
||||
parent[v] = u;
|
||||
key[v] = graph[u][v];
|
||||
}
|
||||
}
|
||||
|
||||
// print the constructed MST
|
||||
printMST(parent, V, graph);
|
||||
}
|
||||
|
||||
public static void main (String[] args)
|
||||
{
|
||||
/* Let us create the following graph
|
||||
2 3
|
||||
(0)--(1)--(2)
|
||||
| / \ |
|
||||
6| 8/ \5 |7
|
||||
| / \ |
|
||||
(3)-------(4)
|
||||
9 */
|
||||
MST t = new MST();
|
||||
int graph[][] = new int[][] {{0, 2, 0, 6, 0},
|
||||
{2, 0, 3, 8, 5},
|
||||
{0, 3, 0, 0, 7},
|
||||
{6, 8, 0, 0, 9},
|
||||
{0, 5, 7, 9, 0},
|
||||
};
|
||||
|
||||
// Print the solution
|
||||
t.primMST(graph);
|
||||
}
|
||||
}
|
||||
42
data_structures/Queues/GenericArrayListQueue.java
Normal file
42
data_structures/Queues/GenericArrayListQueue.java
Normal file
@@ -0,0 +1,42 @@
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class GenericArrayListQueue<T> {
|
||||
ArrayList<T> _queue = new ArrayList<T>();
|
||||
|
||||
private boolean hasElements() {
|
||||
return !_queue.isEmpty();
|
||||
}
|
||||
|
||||
public T peek() {
|
||||
T result = null;
|
||||
if(this.hasElements()) { result = _queue.get(0); }
|
||||
return result;
|
||||
}
|
||||
|
||||
public boolean add(T element) {
|
||||
return _queue.add(element);
|
||||
}
|
||||
|
||||
public T poll() {
|
||||
T result = null;
|
||||
if(this.hasElements()) { result = _queue.remove(0); }
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
GenericArrayListQueue<Integer> queue = new GenericArrayListQueue<Integer>();
|
||||
System.out.println("Running...");
|
||||
assert queue.peek() == null;
|
||||
assert queue.poll() == null;
|
||||
assert queue.add(1) == true;
|
||||
assert queue.peek() == 1;
|
||||
assert queue.add(2) == true;
|
||||
assert queue.peek() == 1;
|
||||
assert queue.poll() == 1;
|
||||
assert queue.peek() == 2;
|
||||
assert queue.poll() == 2;
|
||||
assert queue.peek() == null;
|
||||
assert queue.poll() == null;
|
||||
System.out.println("Finished.");
|
||||
}
|
||||
}
|
||||
98
data_structures/Stacks/StackOfLinkedList.java
Normal file
98
data_structures/Stacks/StackOfLinkedList.java
Normal file
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
*
|
||||
* @author Varun Upadhyay (https://github.com/varunu28)
|
||||
*
|
||||
*/
|
||||
|
||||
// An implementation of a Stack using a Linked List
|
||||
|
||||
class StackOfLinkedList {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
LinkedListStack stack = new LinkedListStack();
|
||||
stack.push(1);
|
||||
stack.push(2);
|
||||
stack.push(3);
|
||||
stack.push(4);
|
||||
|
||||
stack.printStack();
|
||||
|
||||
System.out.println("Size of stack currently is: " + stack.getSize());
|
||||
|
||||
stack.pop();
|
||||
stack.pop();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// A node class
|
||||
|
||||
class Node {
|
||||
public int data;
|
||||
public Node next;
|
||||
|
||||
public Node(int data) {
|
||||
this.data = data;
|
||||
this.next = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A class which implements a stack using a linked list
|
||||
*
|
||||
* Contains all the stack methods : push, pop, printStack, isEmpty
|
||||
**/
|
||||
|
||||
class LinkedListStack {
|
||||
|
||||
Node head = null;
|
||||
int size = 0;
|
||||
|
||||
public void push(int x) {
|
||||
Node n = new Node(x);
|
||||
if (getSize() == 0) {
|
||||
head = n;
|
||||
}
|
||||
else {
|
||||
Node temp = head;
|
||||
n.next = temp;
|
||||
head = n;
|
||||
}
|
||||
size++;
|
||||
}
|
||||
|
||||
public void pop() {
|
||||
if (getSize() == 0) {
|
||||
System.out.println("Empty stack. Nothing to pop");
|
||||
}
|
||||
|
||||
Node temp = head;
|
||||
head = head.next;
|
||||
size--;
|
||||
|
||||
System.out.println("Popped element is: " + temp.data);
|
||||
}
|
||||
|
||||
public void printStack() {
|
||||
|
||||
Node temp = head;
|
||||
System.out.println("Stack is printed as below: ");
|
||||
while (temp != null) {
|
||||
System.out.print(temp.data + " ");
|
||||
temp = temp.next;
|
||||
}
|
||||
System.out.println();
|
||||
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return getSize() == 0;
|
||||
}
|
||||
|
||||
public int getSize() {
|
||||
return size;
|
||||
}
|
||||
|
||||
}
|
||||
100
data_structures/Trees/FindHeightOfTree.java
Normal file
100
data_structures/Trees/FindHeightOfTree.java
Normal file
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
*
|
||||
* @author Varun Upadhyay (https://github.com/varunu28)
|
||||
*
|
||||
*/
|
||||
import java.util.LinkedList;
|
||||
|
||||
public class FindHeightOfTree {
|
||||
|
||||
// Driver Program
|
||||
public static void main(String[] args) {
|
||||
Node tree = new Node(5);
|
||||
tree.insert(3);
|
||||
tree.insert(7);
|
||||
tree.insert(1);
|
||||
tree.insert(-1);
|
||||
tree.insert(29);
|
||||
tree.insert(93);
|
||||
tree.insert(6);
|
||||
tree.insert(0);
|
||||
tree.insert(-5);
|
||||
tree.insert(-6);
|
||||
tree.insert(-8);
|
||||
tree.insert(-1);
|
||||
|
||||
// A level order representation of the tree
|
||||
tree.printLevelOrder();
|
||||
System.out.println();
|
||||
|
||||
System.out.println("Height of the tree is: " + tree.findHeight());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The Node class which initializes a Node of a tree
|
||||
* printLevelOrder: ROOT -> ROOT's CHILDREN -> ROOT's CHILDREN's CHILDREN -> etc
|
||||
* findHeight: Returns the height of the tree i.e. the number of links between root and farthest leaf
|
||||
*/
|
||||
class Node {
|
||||
Node left, right;
|
||||
int data;
|
||||
|
||||
public Node(int data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public void insert (int value) {
|
||||
if (value < data) {
|
||||
if (left == null) {
|
||||
left = new Node(value);
|
||||
}
|
||||
else {
|
||||
left.insert(value);
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (right == null) {
|
||||
right = new Node(value);
|
||||
}
|
||||
else {
|
||||
right.insert(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void printLevelOrder() {
|
||||
LinkedList<Node> queue = new LinkedList<>();
|
||||
queue.add(this);
|
||||
while(!queue.isEmpty()) {
|
||||
Node n = queue.poll();
|
||||
System.out.print(n.data + " ");
|
||||
if (n.left != null) {
|
||||
queue.add(n.left);
|
||||
}
|
||||
if (n.right != null) {
|
||||
queue.add(n.right);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int findHeight() {
|
||||
return findHeight(this);
|
||||
}
|
||||
|
||||
private int findHeight(Node root) {
|
||||
if (root.left == null && root.right == null) {
|
||||
return 0;
|
||||
}
|
||||
else if (root.left != null && root.right != null) {
|
||||
return 1 + Math.max(findHeight(root.left), findHeight(root.right));
|
||||
}
|
||||
else if (root.left == null && root.right != null) {
|
||||
return 1 + findHeight(root.right);
|
||||
}
|
||||
else {
|
||||
return 1 + findHeight(root.left);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import java.util.Queue;
|
||||
import java.util.LinkedList;
|
||||
|
||||
/* Class to represent Tree node */
|
||||
class Node {
|
||||
int data;
|
||||
Node left, right;
|
||||
|
||||
public Node(int item) {
|
||||
data = item;
|
||||
left = null;
|
||||
right = null;
|
||||
}
|
||||
}
|
||||
|
||||
/* Class to print Level Order Traversal */
|
||||
class BinaryTree {
|
||||
|
||||
Node root;
|
||||
|
||||
/* Given a binary tree. Print its nodes in level order
|
||||
using array for implementing queue */
|
||||
void printLevelOrder()
|
||||
{
|
||||
Queue<Node> queue = new LinkedList<Node>();
|
||||
queue.add(root);
|
||||
while (!queue.isEmpty())
|
||||
{
|
||||
|
||||
/* poll() removes the present head.
|
||||
For more information on poll() visit
|
||||
http://www.tutorialspoint.com/java/util/linkedlist_poll.htm */
|
||||
Node tempNode = queue.poll();
|
||||
System.out.print(tempNode.data + " ");
|
||||
|
||||
/*Enqueue left child */
|
||||
if (tempNode.left != null) {
|
||||
queue.add(tempNode.left);
|
||||
}
|
||||
|
||||
/*Enqueue right child */
|
||||
if (tempNode.right != null) {
|
||||
queue.add(tempNode.right);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String args[])
|
||||
{
|
||||
/* creating a binary tree and entering
|
||||
the nodes */
|
||||
BinaryTree tree_level = new BinaryTree();
|
||||
tree_level.root = new Node(1);
|
||||
tree_level.root.left = new Node(2);
|
||||
tree_level.root.right = new Node(3);
|
||||
tree_level.root.left.left = new Node(4);
|
||||
tree_level.root.left.right = new Node(5);
|
||||
|
||||
System.out.println("Level order traversal of binary tree is - ");
|
||||
tree_level.printLevelOrder();
|
||||
}
|
||||
}
|
||||
78
data_structures/Trees/Level Order Traversal.java
Normal file
78
data_structures/Trees/Level Order Traversal.java
Normal file
@@ -0,0 +1,78 @@
|
||||
class Node
|
||||
{
|
||||
int data;
|
||||
Node left, right;
|
||||
public Node(int item)
|
||||
{
|
||||
data = item;
|
||||
left = right = null;
|
||||
}
|
||||
}
|
||||
|
||||
class BinaryTree
|
||||
{
|
||||
// Root of the Binary Tree
|
||||
Node root;
|
||||
|
||||
public BinaryTree()
|
||||
{
|
||||
root = null;
|
||||
}
|
||||
|
||||
/* function to print level order traversal of tree*/
|
||||
void printLevelOrder()
|
||||
{
|
||||
int h = height(root);
|
||||
int i;
|
||||
for (i=1; i<=h; i++)
|
||||
printGivenLevel(root, i);
|
||||
}
|
||||
|
||||
/* Compute the "height" of a tree -- the number of
|
||||
nodes along the longest path from the root node
|
||||
down to the farthest leaf node.*/
|
||||
int height(Node root)
|
||||
{
|
||||
if (root == null)
|
||||
return 0;
|
||||
else
|
||||
{
|
||||
/* compute height of each subtree */
|
||||
int lheight = height(root.left);
|
||||
int rheight = height(root.right);
|
||||
|
||||
/* use the larger one */
|
||||
if (lheight > rheight)
|
||||
return(lheight+1);
|
||||
else return(rheight+1);
|
||||
}
|
||||
}
|
||||
|
||||
/* Print nodes at the given level */
|
||||
void printGivenLevel (Node root ,int level)
|
||||
{
|
||||
if (root == null)
|
||||
return;
|
||||
if (level == 1)
|
||||
System.out.print(root.data + " ");
|
||||
else if (level > 1)
|
||||
{
|
||||
printGivenLevel(root.left, level-1);
|
||||
printGivenLevel(root.right, level-1);
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver program to test above functions */
|
||||
public static void main(String args[])
|
||||
{
|
||||
BinaryTree tree = new BinaryTree();
|
||||
tree.root= new Node(1);
|
||||
tree.root.left= new Node(2);
|
||||
tree.root.right= new Node(3);
|
||||
tree.root.left.left= new Node(4);
|
||||
tree.root.left.right= new Node(5);
|
||||
|
||||
System.out.println("Level order traversal of binary tree is ");
|
||||
tree.printLevelOrder();
|
||||
}
|
||||
}
|
||||
105
data_structures/Trees/Print Top View of Tree.java
Normal file
105
data_structures/Trees/Print Top View of Tree.java
Normal file
@@ -0,0 +1,105 @@
|
||||
// Java program to print top view of Binary tree
|
||||
import java.util.*;
|
||||
|
||||
// Class for a tree node
|
||||
class TreeNode
|
||||
{
|
||||
// Members
|
||||
int key;
|
||||
TreeNode left, right;
|
||||
|
||||
// Constructor
|
||||
public TreeNode(int key)
|
||||
{
|
||||
this.key = key;
|
||||
left = right = null;
|
||||
}
|
||||
}
|
||||
|
||||
// A class to represent a queue item. The queue is used to do Level
|
||||
// order traversal. Every Queue item contains node and horizontal
|
||||
// distance of node from root
|
||||
class QItem
|
||||
{
|
||||
TreeNode node;
|
||||
int hd;
|
||||
public QItem(TreeNode n, int h)
|
||||
{
|
||||
node = n;
|
||||
hd = h;
|
||||
}
|
||||
}
|
||||
|
||||
// Class for a Binary Tree
|
||||
class Tree
|
||||
{
|
||||
TreeNode root;
|
||||
|
||||
// Constructors
|
||||
public Tree() { root = null; }
|
||||
public Tree(TreeNode n) { root = n; }
|
||||
|
||||
// This method prints nodes in top view of binary tree
|
||||
public void printTopView()
|
||||
{
|
||||
// base case
|
||||
if (root == null) { return; }
|
||||
|
||||
// Creates an empty hashset
|
||||
HashSet<Integer> set = new HashSet<>();
|
||||
|
||||
// Create a queue and add root to it
|
||||
Queue<QItem> Q = new LinkedList<QItem>();
|
||||
Q.add(new QItem(root, 0)); // Horizontal distance of root is 0
|
||||
|
||||
// Standard BFS or level order traversal loop
|
||||
while (!Q.isEmpty())
|
||||
{
|
||||
// Remove the front item and get its details
|
||||
QItem qi = Q.remove();
|
||||
int hd = qi.hd;
|
||||
TreeNode n = qi.node;
|
||||
|
||||
// If this is the first node at its horizontal distance,
|
||||
// then this node is in top view
|
||||
if (!set.contains(hd))
|
||||
{
|
||||
set.add(hd);
|
||||
System.out.print(n.key + " ");
|
||||
}
|
||||
|
||||
// Enqueue left and right children of current node
|
||||
if (n.left != null)
|
||||
Q.add(new QItem(n.left, hd-1));
|
||||
if (n.right != null)
|
||||
Q.add(new QItem(n.right, hd+1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Driver class to test above methods
|
||||
public class Main
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
/* Create following Binary Tree
|
||||
1
|
||||
/ \
|
||||
2 3
|
||||
\
|
||||
4
|
||||
\
|
||||
5
|
||||
\
|
||||
6*/
|
||||
TreeNode root = new TreeNode(1);
|
||||
root.left = new TreeNode(2);
|
||||
root.right = new TreeNode(3);
|
||||
root.left.right = new TreeNode(4);
|
||||
root.left.right.right = new TreeNode(5);
|
||||
root.left.right.right.right = new TreeNode(6);
|
||||
Tree t = new Tree(root);
|
||||
System.out.println("Following are nodes in top view of Binary Tree");
|
||||
t.printTopView();
|
||||
}
|
||||
}
|
||||
135
data_structures/Trees/TrieImp.java
Normal file
135
data_structures/Trees/TrieImp.java
Normal file
@@ -0,0 +1,135 @@
|
||||
//Trie Data structure implementation without any libraries */
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Dheeraj Kumar Barnwal (https://github.com/dheeraj92)
|
||||
*
|
||||
*/
|
||||
import java.util.Scanner;
|
||||
|
||||
public class TrieImp {
|
||||
|
||||
public class TrieNode {
|
||||
TrieNode[] child;
|
||||
boolean end;
|
||||
|
||||
public TrieNode(){
|
||||
child = new TrieNode[26];
|
||||
end = false;
|
||||
}
|
||||
}
|
||||
private final TrieNode root;
|
||||
public TrieImp(){
|
||||
root = new TrieNode();
|
||||
}
|
||||
|
||||
public void insert(String word){
|
||||
TrieNode currentNode = root;
|
||||
for(int i=0; i < word.length();i++){
|
||||
TrieNode node = currentNode.child[word.charAt(i)-'a'];
|
||||
if(node == null){
|
||||
node = new TrieNode();
|
||||
currentNode.child[word.charAt(i)-'a']=node;
|
||||
}
|
||||
currentNode = node;
|
||||
}
|
||||
currentNode.end = true;
|
||||
}
|
||||
public boolean search(String word){
|
||||
TrieNode currentNode = root;
|
||||
for(int i=0;i<word.length();i++){
|
||||
char ch = word.charAt(i);
|
||||
TrieNode node = currentNode.child[ch-'a'];
|
||||
if(node == null){
|
||||
return false;
|
||||
}
|
||||
currentNode = node;
|
||||
}
|
||||
return currentNode.end;
|
||||
}
|
||||
|
||||
public boolean delete(String word){
|
||||
TrieNode currentNode = root;
|
||||
for(int i=0;i<word.length();i++){
|
||||
char ch = word.charAt(i);
|
||||
TrieNode node = currentNode.child[ch-'a'];
|
||||
if(node == null){
|
||||
return false;
|
||||
}
|
||||
currentNode = node;
|
||||
}
|
||||
if(currentNode.end == true){
|
||||
currentNode.end = false;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static void sop(String print){
|
||||
System.out.println(print);
|
||||
}
|
||||
|
||||
//Regex to check if word contains only a-z character
|
||||
public static boolean isValid(String word){
|
||||
return word.matches("^[a-z]+$");
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
TrieImp obj = new TrieImp();
|
||||
String word;
|
||||
@SuppressWarnings("resource")
|
||||
Scanner scan = new Scanner(System.in);
|
||||
sop("string should contain only a-z character for all operation");
|
||||
while(true){
|
||||
sop("1. Insert\n2. Search\n3. Delete\n4. Quit");
|
||||
try{
|
||||
int t = scan.nextInt();
|
||||
switch (t) {
|
||||
case 1:
|
||||
word = scan.next();
|
||||
if(isValid(word))
|
||||
obj.insert(word);
|
||||
else
|
||||
sop("Invalid string: allowed only a-z");
|
||||
break;
|
||||
case 2:
|
||||
word = scan.next();
|
||||
boolean resS=false;
|
||||
if(isValid(word))
|
||||
resS = obj.search(word);
|
||||
else
|
||||
sop("Invalid string: allowed only a-z");
|
||||
if(resS)
|
||||
sop("word found");
|
||||
else
|
||||
sop("word not found");
|
||||
break;
|
||||
case 3:
|
||||
word = scan.next();
|
||||
boolean resD=false;
|
||||
if(isValid(word))
|
||||
resD = obj.delete(word);
|
||||
else
|
||||
sop("Invalid string: allowed only a-z");
|
||||
if(resD){
|
||||
sop("word got deleted successfully");
|
||||
}else{
|
||||
sop("word not found");
|
||||
}
|
||||
break;
|
||||
case 4:
|
||||
sop("Quit successfully");
|
||||
System.exit(1);
|
||||
break;
|
||||
default:
|
||||
sop("Input int from 1-4");
|
||||
break;
|
||||
}
|
||||
}catch(Exception e){
|
||||
String badInput = scan.next();
|
||||
sop("This is bad input: " + badInput);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
62
data_structures/Trees/Valid BST or not.java
Normal file
62
data_structures/Trees/Valid BST or not.java
Normal file
@@ -0,0 +1,62 @@
|
||||
class Node
|
||||
{
|
||||
int data;
|
||||
Node left, right;
|
||||
|
||||
public Node(int item)
|
||||
{
|
||||
data = item;
|
||||
left = right = null;
|
||||
}
|
||||
}
|
||||
|
||||
public class BinaryTree
|
||||
{
|
||||
//Root of the Binary Tree
|
||||
Node root;
|
||||
|
||||
/* can give min and max value according to your code or
|
||||
can write a function to find min and max value of tree. */
|
||||
|
||||
/* returns true if given search tree is binary
|
||||
search tree (efficient version) */
|
||||
boolean isBST() {
|
||||
return isBSTUtil(root, Integer.MIN_VALUE,
|
||||
Integer.MAX_VALUE);
|
||||
}
|
||||
|
||||
/* Returns true if the given tree is a BST and its
|
||||
values are >= min and <= max. */
|
||||
boolean isBSTUtil(Node node, int min, int max)
|
||||
{
|
||||
/* an empty tree is BST */
|
||||
if (node == null)
|
||||
return true;
|
||||
|
||||
/* false if this node violates the min/max constraints */
|
||||
if (node.data < min || node.data > max)
|
||||
return false;
|
||||
|
||||
/* otherwise check the subtrees recursively
|
||||
tightening the min/max constraints */
|
||||
// Allow only distinct values
|
||||
return (isBSTUtil(node.left, min, node.data-1) &&
|
||||
isBSTUtil(node.right, node.data+1, max));
|
||||
}
|
||||
|
||||
/* Driver program to test above functions */
|
||||
public static void main(String args[])
|
||||
{
|
||||
BinaryTree tree = new BinaryTree();
|
||||
tree.root = new Node(4);
|
||||
tree.root.left = new Node(2);
|
||||
tree.root.right = new Node(5);
|
||||
tree.root.left.left = new Node(1);
|
||||
tree.root.left.right = new Node(3);
|
||||
|
||||
if (tree.isBST())
|
||||
System.out.println("IS BST");
|
||||
else
|
||||
System.out.println("Not a BST");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user