mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-27 14:34:05 +08:00
Format code with prettier (#3375)
This commit is contained in:
@ -1,4 +1,3 @@
|
||||
|
||||
package com.thealgorithms.datastructures.trees;
|
||||
|
||||
/*
|
||||
@ -27,111 +26,106 @@ AVLTree tree=new AVLTree();
|
||||
|
||||
*/
|
||||
|
||||
|
||||
|
||||
public class AVLSimple {
|
||||
private class Node{
|
||||
int data;
|
||||
int height;
|
||||
Node left;
|
||||
Node right;
|
||||
Node(int data){
|
||||
this.data=data;
|
||||
this.height=1;
|
||||
}
|
||||
|
||||
}
|
||||
private Node root;
|
||||
public void insert(int data) {
|
||||
this.root=insert(this.root,data);
|
||||
}
|
||||
private Node insert(Node node,int item) {
|
||||
if(node==null) {
|
||||
Node add=new Node(item);
|
||||
return add;
|
||||
}
|
||||
if(node.data>item) {
|
||||
node.left=insert(node.left,item);
|
||||
}
|
||||
if(node.data<item) {
|
||||
node.right=insert(node.right,item);
|
||||
}
|
||||
node.height=Math.max(height(node.left),height(node.right))+1;
|
||||
int bf=bf(node);
|
||||
//LL case
|
||||
if(bf>1&&item<node.left.data)
|
||||
return rightRotate(node);
|
||||
//RR case
|
||||
if(bf<-1&&item>node.right.data)
|
||||
return leftRotate(node);
|
||||
//RL case
|
||||
if(bf<-1&&item<node.right.data) {
|
||||
node.right=rightRotate(node.right);
|
||||
return leftRotate(node);
|
||||
}
|
||||
//LR case
|
||||
if(bf>1&&item>node.left.data) {
|
||||
node.left=leftRotate(node.left);
|
||||
return rightRotate(node);
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
public void display() {
|
||||
this.display(this.root);
|
||||
System.out.println(this.root.height);
|
||||
}
|
||||
private void display (Node node) {
|
||||
String str="";
|
||||
if(node.left!=null)
|
||||
str+=node.left.data+"=>";
|
||||
else
|
||||
str+="END=>";
|
||||
str+=node.data+"";
|
||||
if(node.right!=null)
|
||||
str+="<="+node.right.data;
|
||||
else
|
||||
str+="<=END";
|
||||
System.out.println(str);
|
||||
if(node.left!=null)
|
||||
display(node.left);
|
||||
if(node.right!=null)
|
||||
display(node.right);
|
||||
}
|
||||
private int height(Node node) {
|
||||
if(node==null) {
|
||||
return 0;
|
||||
}
|
||||
return node.height;
|
||||
|
||||
}
|
||||
private int bf(Node node) {
|
||||
if(node==null)
|
||||
return 0;
|
||||
return height(node.left)-height(node.right);
|
||||
}
|
||||
|
||||
private Node rightRotate(Node c) {
|
||||
Node b=c.left;
|
||||
Node T3=b.right;
|
||||
|
||||
b.right=c;
|
||||
c.left=T3;
|
||||
c.height=Math.max(height(c.left),height(c.right))+1;
|
||||
b.height=Math.max(height(b.left),height(b.right))+1;
|
||||
return b;
|
||||
|
||||
}
|
||||
private Node leftRotate(Node c) {
|
||||
Node b=c.right;
|
||||
Node T3=b.left;
|
||||
|
||||
b.left=c;
|
||||
c.right=T3;
|
||||
c.height=Math.max(height(c.left),height(c.right))+1;
|
||||
b.height=Math.max(height(b.left),height(b.right))+1;
|
||||
return b;
|
||||
|
||||
}
|
||||
|
||||
private class Node {
|
||||
|
||||
int data;
|
||||
int height;
|
||||
Node left;
|
||||
Node right;
|
||||
|
||||
Node(int data) {
|
||||
this.data = data;
|
||||
this.height = 1;
|
||||
}
|
||||
}
|
||||
|
||||
private Node root;
|
||||
|
||||
public void insert(int data) {
|
||||
this.root = insert(this.root, data);
|
||||
}
|
||||
|
||||
private Node insert(Node node, int item) {
|
||||
if (node == null) {
|
||||
Node add = new Node(item);
|
||||
return add;
|
||||
}
|
||||
if (node.data > item) {
|
||||
node.left = insert(node.left, item);
|
||||
}
|
||||
if (node.data < item) {
|
||||
node.right = insert(node.right, item);
|
||||
}
|
||||
node.height = Math.max(height(node.left), height(node.right)) + 1;
|
||||
int bf = bf(node);
|
||||
//LL case
|
||||
if (bf > 1 && item < node.left.data) return rightRotate(node);
|
||||
//RR case
|
||||
if (bf < -1 && item > node.right.data) return leftRotate(node);
|
||||
//RL case
|
||||
if (bf < -1 && item < node.right.data) {
|
||||
node.right = rightRotate(node.right);
|
||||
return leftRotate(node);
|
||||
}
|
||||
//LR case
|
||||
if (bf > 1 && item > node.left.data) {
|
||||
node.left = leftRotate(node.left);
|
||||
return rightRotate(node);
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
public void display() {
|
||||
this.display(this.root);
|
||||
System.out.println(this.root.height);
|
||||
}
|
||||
|
||||
private void display(Node node) {
|
||||
String str = "";
|
||||
if (node.left != null) str += node.left.data + "=>"; else str +=
|
||||
"END=>";
|
||||
str += node.data + "";
|
||||
if (node.right != null) str += "<=" + node.right.data; else str +=
|
||||
"<=END";
|
||||
System.out.println(str);
|
||||
if (node.left != null) display(node.left);
|
||||
if (node.right != null) display(node.right);
|
||||
}
|
||||
|
||||
private int height(Node node) {
|
||||
if (node == null) {
|
||||
return 0;
|
||||
}
|
||||
return node.height;
|
||||
}
|
||||
|
||||
private int bf(Node node) {
|
||||
if (node == null) return 0;
|
||||
return height(node.left) - height(node.right);
|
||||
}
|
||||
|
||||
private Node rightRotate(Node c) {
|
||||
Node b = c.left;
|
||||
Node T3 = b.right;
|
||||
|
||||
b.right = c;
|
||||
c.left = T3;
|
||||
c.height = Math.max(height(c.left), height(c.right)) + 1;
|
||||
b.height = Math.max(height(b.left), height(b.right)) + 1;
|
||||
return b;
|
||||
}
|
||||
|
||||
private Node leftRotate(Node c) {
|
||||
Node b = c.right;
|
||||
Node T3 = b.left;
|
||||
|
||||
b.left = c;
|
||||
c.right = T3;
|
||||
c.height = Math.max(height(c.left), height(c.right)) + 1;
|
||||
b.height = Math.max(height(b.left), height(b.right)) + 1;
|
||||
return b;
|
||||
}
|
||||
}
|
||||
|
@ -105,7 +105,6 @@ public class AVLTree {
|
||||
} else {
|
||||
n = rotateLeftThenRight(n);
|
||||
}
|
||||
|
||||
} else if (n.balance == 2) {
|
||||
if (height(n.right.right) >= height(n.right.left)) {
|
||||
n = rotateLeft(n);
|
||||
@ -122,7 +121,6 @@ public class AVLTree {
|
||||
}
|
||||
|
||||
private Node rotateLeft(Node a) {
|
||||
|
||||
Node b = a.right;
|
||||
b.parent = a.parent;
|
||||
|
||||
@ -149,7 +147,6 @@ public class AVLTree {
|
||||
}
|
||||
|
||||
private Node rotateRight(Node a) {
|
||||
|
||||
Node b = a.left;
|
||||
b.parent = a.parent;
|
||||
|
||||
|
@ -42,7 +42,9 @@ public class BSTIterative {
|
||||
tree.remove(2);
|
||||
assert !tree.find(2) : "2 was just deleted from BST";
|
||||
tree.remove(1);
|
||||
assert !tree.find(1) : "Since 1 was not present so find deleting would do no change";
|
||||
assert !tree.find(
|
||||
1
|
||||
) : "Since 1 was not present so find deleting would do no change";
|
||||
tree.add(30);
|
||||
tree.add(40);
|
||||
assert tree.find(40) : "40 was inserted but not found";
|
||||
@ -64,7 +66,7 @@ public class BSTIterative {
|
||||
Node temp = this.root;
|
||||
int rightOrLeft = -1;
|
||||
/* Finds the proper place this node can
|
||||
* be placed in according to rules of BST.
|
||||
* be placed in according to rules of BST.
|
||||
*/
|
||||
while (temp != null) {
|
||||
if (temp.data > data) {
|
||||
@ -81,18 +83,18 @@ public class BSTIterative {
|
||||
}
|
||||
}
|
||||
/* Creates a newNode with the value passed
|
||||
* Since this data doesn't already exists
|
||||
* Since this data doesn't already exists
|
||||
*/
|
||||
Node newNode = new Node(data);
|
||||
/* If the parent node is null
|
||||
* then the insertion is to be done in
|
||||
* root itself.
|
||||
* then the insertion is to be done in
|
||||
* root itself.
|
||||
*/
|
||||
if (parent == null) {
|
||||
this.root = newNode;
|
||||
} else {
|
||||
/* Check if insertion is to be made in
|
||||
* left or right subtree.
|
||||
* left or right subtree.
|
||||
*/
|
||||
if (rightOrLeft == 0) {
|
||||
parent.left = newNode;
|
||||
@ -112,11 +114,11 @@ public class BSTIterative {
|
||||
Node temp = this.root;
|
||||
int rightOrLeft = -1;
|
||||
/* Find the parent of the node and node itself
|
||||
* That is to be deleted.
|
||||
* parent variable store parent
|
||||
* temp stores node itself.
|
||||
* rightOrLeft use to keep track weather child
|
||||
* is left or right subtree
|
||||
* That is to be deleted.
|
||||
* parent variable store parent
|
||||
* temp stores node itself.
|
||||
* rightOrLeft use to keep track weather child
|
||||
* is left or right subtree
|
||||
*/
|
||||
while (temp != null) {
|
||||
if (temp.data == data) {
|
||||
@ -132,7 +134,7 @@ public class BSTIterative {
|
||||
}
|
||||
}
|
||||
/* If temp is null than node with given value is not
|
||||
* present in our tree.
|
||||
* present in our tree.
|
||||
*/
|
||||
if (temp != null) {
|
||||
Node replacement; // used to store the new values for replacing nodes
|
||||
@ -146,10 +148,10 @@ public class BSTIterative {
|
||||
temp.right = null;
|
||||
} else {
|
||||
/* If both left and right child are present
|
||||
* we replace this nodes data with
|
||||
* leftmost node's data in its right subtree
|
||||
* to maintain the balance of BST.
|
||||
* And then delete that node
|
||||
* we replace this nodes data with
|
||||
* leftmost node's data in its right subtree
|
||||
* to maintain the balance of BST.
|
||||
* And then delete that node
|
||||
*/
|
||||
if (temp.right.left == null) {
|
||||
temp.data = temp.right.data;
|
||||
@ -168,7 +170,7 @@ public class BSTIterative {
|
||||
}
|
||||
}
|
||||
/* Change references of parent after
|
||||
* deleting the child.
|
||||
* deleting the child.
|
||||
*/
|
||||
if (parent == null) {
|
||||
this.root = replacement;
|
||||
|
@ -44,7 +44,9 @@ public class BSTRecursive {
|
||||
tree.remove(9);
|
||||
assert !tree.find(9) : "9 was just deleted from BST";
|
||||
tree.remove(1);
|
||||
assert !tree.find(1) : "Since 1 was not present so find deleting would do no change";
|
||||
assert !tree.find(
|
||||
1
|
||||
) : "Since 1 was not present so find deleting would do no change";
|
||||
tree.add(20);
|
||||
tree.add(70);
|
||||
assert tree.find(70) : "70 was inserted but not found";
|
||||
|
@ -44,7 +44,9 @@ public class BSTRecursiveGeneric<T extends Comparable<T>> {
|
||||
integerTree.remove(9);
|
||||
assert !integerTree.find(9) : "9 was just deleted from BST";
|
||||
integerTree.remove(1);
|
||||
assert !integerTree.find(1) : "Since 1 was not present so find deleting would do no change";
|
||||
assert !integerTree.find(
|
||||
1
|
||||
) : "Since 1 was not present so find deleting would do no change";
|
||||
integerTree.add(20);
|
||||
integerTree.add(70);
|
||||
assert integerTree.find(70) : "70 was inserted but not found";
|
||||
@ -66,7 +68,9 @@ public class BSTRecursiveGeneric<T extends Comparable<T>> {
|
||||
stringTree.remove("date");
|
||||
assert !stringTree.find("date") : "date was just deleted from BST";
|
||||
stringTree.remove("boy");
|
||||
assert !stringTree.find("boy") : "Since boy was not present so deleting would do no change";
|
||||
assert !stringTree.find(
|
||||
"boy"
|
||||
) : "Since boy was not present so deleting would do no change";
|
||||
stringTree.add("india");
|
||||
stringTree.add("hills");
|
||||
assert stringTree.find("hills") : "hills was inserted but not found";
|
||||
@ -75,7 +79,6 @@ public class BSTRecursiveGeneric<T extends Comparable<T>> {
|
||||
banana hills india pineapple
|
||||
*/
|
||||
stringTree.inorder();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -1,7 +1,7 @@
|
||||
package com.thealgorithms.datastructures.trees;
|
||||
|
||||
import java.util.Queue;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Queue;
|
||||
|
||||
/**
|
||||
* This entire class is used to build a Binary Tree data structure. There is the
|
||||
|
@ -1,7 +1,7 @@
|
||||
package com.thealgorithms.datastructures.trees;
|
||||
|
||||
import java.util.Stack;
|
||||
import java.util.HashMap;
|
||||
import java.util.Stack;
|
||||
|
||||
/**
|
||||
* This class will check if a BinaryTree is balanced. A balanced binary tree is
|
||||
@ -80,7 +80,11 @@ public class CheckIfBinaryTreeBalanced {
|
||||
* @param depth The current depth of the node
|
||||
* @param isBalanced The array of length 1 keeping track of our balance
|
||||
*/
|
||||
private int isBalancedRecursive(BTNode node, int depth, boolean[] isBalanced) {
|
||||
private int isBalancedRecursive(
|
||||
BTNode node,
|
||||
int depth,
|
||||
boolean[] isBalanced
|
||||
) {
|
||||
// If the node is null, we should not explore it and the height is 0
|
||||
// If the tree is already not balanced, might as well stop because we
|
||||
// can't make it balanced now!
|
||||
@ -90,7 +94,11 @@ public class CheckIfBinaryTreeBalanced {
|
||||
|
||||
// Visit the left and right children, incrementing their depths by 1
|
||||
int leftHeight = isBalancedRecursive(node.left, depth + 1, isBalanced);
|
||||
int rightHeight = isBalancedRecursive(node.right, depth + 1, isBalanced);
|
||||
int rightHeight = isBalancedRecursive(
|
||||
node.right,
|
||||
depth + 1,
|
||||
isBalanced
|
||||
);
|
||||
|
||||
// If the height of either of the left or right subtrees differ by more
|
||||
// than 1, we cannot be balanced
|
||||
@ -166,7 +174,10 @@ public class CheckIfBinaryTreeBalanced {
|
||||
|
||||
// The height of the subtree containing this node is the
|
||||
// max of the left and right subtree heighs plus 1
|
||||
subtreeHeights.put(node, Math.max(rightHeight, leftHeight) + 1);
|
||||
subtreeHeights.put(
|
||||
node,
|
||||
Math.max(rightHeight, leftHeight) + 1
|
||||
);
|
||||
|
||||
// We've now visited this node, so we pop it from the stack
|
||||
nodeStack.pop();
|
||||
|
@ -12,10 +12,10 @@ import com.thealgorithms.datastructures.trees.BinaryTree.Node;
|
||||
public class CreateBSTFromSortedArray {
|
||||
|
||||
public static void main(String[] args) {
|
||||
test(new int[]{});
|
||||
test(new int[]{1, 2, 3});
|
||||
test(new int[]{1, 2, 3, 4, 5});
|
||||
test(new int[]{1, 2, 3, 4, 5, 6, 7});
|
||||
test(new int[] {});
|
||||
test(new int[] { 1, 2, 3 });
|
||||
test(new int[] { 1, 2, 3, 4, 5 });
|
||||
test(new int[] { 1, 2, 3, 4, 5, 6, 7 });
|
||||
}
|
||||
|
||||
private static void test(int[] array) {
|
||||
|
@ -1,8 +1,8 @@
|
||||
package com.thealgorithms.datastructures.trees;
|
||||
|
||||
import com.thealgorithms.datastructures.trees.BinaryTree.Node;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import com.thealgorithms.datastructures.trees.BinaryTree.Node;
|
||||
|
||||
/**
|
||||
* Approach: Naive Solution: Create root node from first value present in
|
||||
@ -21,17 +21,27 @@ import com.thealgorithms.datastructures.trees.BinaryTree.Node;
|
||||
public class CreateBinaryTreeFromInorderPreorder {
|
||||
|
||||
public static void main(String[] args) {
|
||||
test(new Integer[]{}, new Integer[]{}); // empty tree
|
||||
test(new Integer[]{1}, new Integer[]{1}); // single node tree
|
||||
test(new Integer[]{1, 2, 3, 4}, new Integer[]{1, 2, 3, 4}); // right skewed tree
|
||||
test(new Integer[]{1, 2, 3, 4}, new Integer[]{4, 3, 2, 1}); // left skewed tree
|
||||
test(new Integer[]{3, 9, 20, 15, 7}, new Integer[]{9, 3, 15, 20, 7}); // normal tree
|
||||
test(new Integer[] {}, new Integer[] {}); // empty tree
|
||||
test(new Integer[] { 1 }, new Integer[] { 1 }); // single node tree
|
||||
test(new Integer[] { 1, 2, 3, 4 }, new Integer[] { 1, 2, 3, 4 }); // right skewed tree
|
||||
test(new Integer[] { 1, 2, 3, 4 }, new Integer[] { 4, 3, 2, 1 }); // left skewed tree
|
||||
test(
|
||||
new Integer[] { 3, 9, 20, 15, 7 },
|
||||
new Integer[] { 9, 3, 15, 20, 7 }
|
||||
); // normal tree
|
||||
}
|
||||
|
||||
private static void test(final Integer[] preorder, final Integer[] inorder) {
|
||||
System.out.println("\n====================================================");
|
||||
private static void test(
|
||||
final Integer[] preorder,
|
||||
final Integer[] inorder
|
||||
) {
|
||||
System.out.println(
|
||||
"\n===================================================="
|
||||
);
|
||||
System.out.println("Naive Solution...");
|
||||
BinaryTree root = new BinaryTree(createTree(preorder, inorder, 0, 0, inorder.length));
|
||||
BinaryTree root = new BinaryTree(
|
||||
createTree(preorder, inorder, 0, 0, inorder.length)
|
||||
);
|
||||
System.out.println("Preorder Traversal: ");
|
||||
root.preOrder(root.getRoot());
|
||||
System.out.println("\nInorder Traversal: ");
|
||||
@ -43,7 +53,9 @@ public class CreateBinaryTreeFromInorderPreorder {
|
||||
for (int i = 0; i < inorder.length; i++) {
|
||||
map.put(inorder[i], i);
|
||||
}
|
||||
BinaryTree optimizedRoot = new BinaryTree(createTreeOptimized(preorder, inorder, 0, 0, inorder.length, map));
|
||||
BinaryTree optimizedRoot = new BinaryTree(
|
||||
createTreeOptimized(preorder, inorder, 0, 0, inorder.length, map)
|
||||
);
|
||||
System.out.println("\n\nOptimized solution...");
|
||||
System.out.println("Preorder Traversal: ");
|
||||
optimizedRoot.preOrder(root.getRoot());
|
||||
@ -53,8 +65,13 @@ public class CreateBinaryTreeFromInorderPreorder {
|
||||
optimizedRoot.postOrder(root.getRoot());
|
||||
}
|
||||
|
||||
private static Node createTree(final Integer[] preorder, final Integer[] inorder,
|
||||
final int preStart, final int inStart, final int size) {
|
||||
private static Node createTree(
|
||||
final Integer[] preorder,
|
||||
final Integer[] inorder,
|
||||
final int preStart,
|
||||
final int inStart,
|
||||
final int size
|
||||
) {
|
||||
if (size == 0) {
|
||||
return null;
|
||||
}
|
||||
@ -66,16 +83,33 @@ public class CreateBinaryTreeFromInorderPreorder {
|
||||
}
|
||||
int leftNodesCount = i - inStart;
|
||||
int rightNodesCount = size - leftNodesCount - 1;
|
||||
root.left = createTree(preorder, inorder, preStart + 1, inStart, leftNodesCount);
|
||||
root.right = createTree(preorder, inorder, preStart + leftNodesCount + 1, i + 1,
|
||||
rightNodesCount);
|
||||
root.left =
|
||||
createTree(
|
||||
preorder,
|
||||
inorder,
|
||||
preStart + 1,
|
||||
inStart,
|
||||
leftNodesCount
|
||||
);
|
||||
root.right =
|
||||
createTree(
|
||||
preorder,
|
||||
inorder,
|
||||
preStart + leftNodesCount + 1,
|
||||
i + 1,
|
||||
rightNodesCount
|
||||
);
|
||||
return root;
|
||||
|
||||
}
|
||||
|
||||
private static Node createTreeOptimized(final Integer[] preorder, final Integer[] inorder,
|
||||
final int preStart, final int inStart, final int size,
|
||||
final Map<Integer, Integer> inorderMap) {
|
||||
private static Node createTreeOptimized(
|
||||
final Integer[] preorder,
|
||||
final Integer[] inorder,
|
||||
final int preStart,
|
||||
final int inStart,
|
||||
final int size,
|
||||
final Map<Integer, Integer> inorderMap
|
||||
) {
|
||||
if (size == 0) {
|
||||
return null;
|
||||
}
|
||||
@ -84,11 +118,24 @@ public class CreateBinaryTreeFromInorderPreorder {
|
||||
int i = inorderMap.get(preorder[preStart]);
|
||||
int leftNodesCount = i - inStart;
|
||||
int rightNodesCount = size - leftNodesCount - 1;
|
||||
root.left = createTreeOptimized(preorder, inorder, preStart + 1, inStart,
|
||||
leftNodesCount, inorderMap);
|
||||
root.right = createTreeOptimized(preorder, inorder, preStart + leftNodesCount + 1,
|
||||
i + 1, rightNodesCount, inorderMap);
|
||||
root.left =
|
||||
createTreeOptimized(
|
||||
preorder,
|
||||
inorder,
|
||||
preStart + 1,
|
||||
inStart,
|
||||
leftNodesCount,
|
||||
inorderMap
|
||||
);
|
||||
root.right =
|
||||
createTreeOptimized(
|
||||
preorder,
|
||||
inorder,
|
||||
preStart + leftNodesCount + 1,
|
||||
i + 1,
|
||||
rightNodesCount,
|
||||
inorderMap
|
||||
);
|
||||
return root;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -35,7 +35,9 @@ public class GenericTree {
|
||||
if (node == null) {
|
||||
System.out.println("Enter root's data");
|
||||
} else {
|
||||
System.out.println("Enter data of parent of index " + node.data + " " + childindx);
|
||||
System.out.println(
|
||||
"Enter data of parent of index " + node.data + " " + childindx
|
||||
);
|
||||
}
|
||||
// input
|
||||
node = new Node();
|
||||
|
@ -34,9 +34,15 @@ public class KDTree {
|
||||
* @param points Array of initial points
|
||||
*/
|
||||
KDTree(Point[] points) {
|
||||
if (points.length == 0) throw new IllegalArgumentException("Points array cannot be empty");
|
||||
if (points.length == 0) throw new IllegalArgumentException(
|
||||
"Points array cannot be empty"
|
||||
);
|
||||
this.k = points[0].getDimension();
|
||||
for (Point point : points) if (point.getDimension() != k) throw new IllegalArgumentException("Points must have the same dimension");
|
||||
for (Point point : points) if (
|
||||
point.getDimension() != k
|
||||
) throw new IllegalArgumentException(
|
||||
"Points must have the same dimension"
|
||||
);
|
||||
this.root = build(points, 0);
|
||||
}
|
||||
|
||||
@ -47,16 +53,24 @@ public class KDTree {
|
||||
*
|
||||
*/
|
||||
KDTree(int[][] pointsCoordinates) {
|
||||
if (pointsCoordinates.length == 0) throw new IllegalArgumentException("Points array cannot be empty");
|
||||
if (pointsCoordinates.length == 0) throw new IllegalArgumentException(
|
||||
"Points array cannot be empty"
|
||||
);
|
||||
this.k = pointsCoordinates[0].length;
|
||||
Point[] points = Arrays.stream(pointsCoordinates)
|
||||
.map(Point::new)
|
||||
.toArray(Point[]::new);
|
||||
for (Point point : points) if (point.getDimension() != k) throw new IllegalArgumentException("Points must have the same dimension");
|
||||
Point[] points = Arrays
|
||||
.stream(pointsCoordinates)
|
||||
.map(Point::new)
|
||||
.toArray(Point[]::new);
|
||||
for (Point point : points) if (
|
||||
point.getDimension() != k
|
||||
) throw new IllegalArgumentException(
|
||||
"Points must have the same dimension"
|
||||
);
|
||||
this.root = build(points, 0);
|
||||
}
|
||||
|
||||
static class Point {
|
||||
|
||||
int[] coordinates;
|
||||
|
||||
public int getCoordinate(int i) {
|
||||
@ -93,7 +107,7 @@ public class KDTree {
|
||||
*
|
||||
* @return The comparable distance between the two points
|
||||
*/
|
||||
static public int comparableDistance(Point p1, Point p2) {
|
||||
public static int comparableDistance(Point p1, Point p2) {
|
||||
int distance = 0;
|
||||
for (int i = 0; i < p1.getDimension(); i++) {
|
||||
int t = p1.getCoordinate(i) - p2.getCoordinate(i);
|
||||
@ -111,7 +125,11 @@ public class KDTree {
|
||||
*
|
||||
* @return The distance between the two points
|
||||
*/
|
||||
static public int comparableDistanceExceptAxis(Point p1, Point p2, int axis) {
|
||||
public static int comparableDistanceExceptAxis(
|
||||
Point p1,
|
||||
Point p2,
|
||||
int axis
|
||||
) {
|
||||
int distance = 0;
|
||||
for (int i = 0; i < p1.getDimension(); i++) {
|
||||
if (i == axis) continue;
|
||||
@ -122,8 +140,8 @@ public class KDTree {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static class Node {
|
||||
|
||||
private Point point;
|
||||
private int axis; // 0 for x, 1 for y, 2 for z, etc.
|
||||
|
||||
@ -159,8 +177,9 @@ public class KDTree {
|
||||
* @return The nearest child Node
|
||||
*/
|
||||
public Node getNearChild(Point point) {
|
||||
if (point.getCoordinate(axis) < this.point.getCoordinate(axis)) return left;
|
||||
else return right;
|
||||
if (
|
||||
point.getCoordinate(axis) < this.point.getCoordinate(axis)
|
||||
) return left; else return right;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -171,8 +190,9 @@ public class KDTree {
|
||||
* @return The farthest child Node
|
||||
*/
|
||||
public Node getFarChild(Point point) {
|
||||
if (point.getCoordinate(axis) < this.point.getCoordinate(axis)) return right;
|
||||
else return left;
|
||||
if (
|
||||
point.getCoordinate(axis) < this.point.getCoordinate(axis)
|
||||
) return right; else return left;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -201,11 +221,18 @@ public class KDTree {
|
||||
if (points.length == 0) return null;
|
||||
int axis = depth % k;
|
||||
if (points.length == 1) return new Node(points[0], axis);
|
||||
Arrays.sort(points, Comparator.comparingInt(o -> o.getCoordinate(axis)));
|
||||
Arrays.sort(
|
||||
points,
|
||||
Comparator.comparingInt(o -> o.getCoordinate(axis))
|
||||
);
|
||||
int median = points.length >> 1;
|
||||
Node node = new Node(points[median], axis);
|
||||
node.left = build(Arrays.copyOfRange(points, 0, median), depth + 1);
|
||||
node.right = build(Arrays.copyOfRange(points, median + 1, points.length), depth + 1);
|
||||
node.right =
|
||||
build(
|
||||
Arrays.copyOfRange(points, median + 1, points.length),
|
||||
depth + 1
|
||||
);
|
||||
return node;
|
||||
}
|
||||
|
||||
@ -216,7 +243,9 @@ public class KDTree {
|
||||
*
|
||||
*/
|
||||
public void insert(Point point) {
|
||||
if (point.getDimension() != k) throw new IllegalArgumentException("Point has wrong dimension");
|
||||
if (point.getDimension() != k) throw new IllegalArgumentException(
|
||||
"Point has wrong dimension"
|
||||
);
|
||||
root = insert(root, point, 0);
|
||||
}
|
||||
|
||||
@ -232,8 +261,9 @@ public class KDTree {
|
||||
private Node insert(Node root, Point point, int depth) {
|
||||
int axis = depth % k;
|
||||
if (root == null) return new Node(point, axis);
|
||||
if (point.getCoordinate(axis) < root.getAxisCoordinate()) root.left = insert(root.left, point, depth + 1);
|
||||
else root.right = insert(root.right, point, depth + 1);
|
||||
if (point.getCoordinate(axis) < root.getAxisCoordinate()) root.left =
|
||||
insert(root.left, point, depth + 1); else root.right =
|
||||
insert(root.right, point, depth + 1);
|
||||
|
||||
return root;
|
||||
}
|
||||
@ -246,7 +276,9 @@ public class KDTree {
|
||||
* @return The Node corresponding to the specified point
|
||||
*/
|
||||
public Optional<Node> search(Point point) {
|
||||
if (point.getDimension() != k) throw new IllegalArgumentException("Point has wrong dimension");
|
||||
if (point.getDimension() != k) throw new IllegalArgumentException(
|
||||
"Point has wrong dimension"
|
||||
);
|
||||
return search(root, point);
|
||||
}
|
||||
|
||||
@ -264,7 +296,6 @@ public class KDTree {
|
||||
return search(root.getNearChild(point), point);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Find a point with minimum value in specified axis in the KDTree
|
||||
*
|
||||
@ -292,14 +323,15 @@ public class KDTree {
|
||||
} else {
|
||||
Node left = findMin(root.left, axis);
|
||||
Node right = findMin(root.right, axis);
|
||||
Node[] candidates = {left, root, right};
|
||||
return Arrays.stream(candidates)
|
||||
.filter(Objects::nonNull)
|
||||
.min(Comparator.comparingInt(a -> a.point.getCoordinate(axis))).orElse(null);
|
||||
Node[] candidates = { left, root, right };
|
||||
return Arrays
|
||||
.stream(candidates)
|
||||
.filter(Objects::nonNull)
|
||||
.min(Comparator.comparingInt(a -> a.point.getCoordinate(axis)))
|
||||
.orElse(null);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Find a point with maximum value in specified axis in the KDTree
|
||||
*
|
||||
@ -327,10 +359,12 @@ public class KDTree {
|
||||
} else {
|
||||
Node left = findMax(root.left, axis);
|
||||
Node right = findMax(root.right, axis);
|
||||
Node[] candidates = {left, root, right};
|
||||
return Arrays.stream(candidates)
|
||||
.filter(Objects::nonNull)
|
||||
.max(Comparator.comparingInt(a -> a.point.getCoordinate(axis))).orElse(null);
|
||||
Node[] candidates = { left, root, right };
|
||||
return Arrays
|
||||
.stream(candidates)
|
||||
.filter(Objects::nonNull)
|
||||
.max(Comparator.comparingInt(a -> a.point.getCoordinate(axis)))
|
||||
.orElse(null);
|
||||
}
|
||||
}
|
||||
|
||||
@ -340,7 +374,8 @@ public class KDTree {
|
||||
* @param point the point to delete
|
||||
* */
|
||||
public void delete(Point point) {
|
||||
Node node = search(point).orElseThrow(() -> new IllegalArgumentException("Point not found"));
|
||||
Node node = search(point)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Point not found"));
|
||||
root = delete(root, node);
|
||||
}
|
||||
|
||||
@ -365,8 +400,10 @@ public class KDTree {
|
||||
root.left = delete(root.left, min);
|
||||
} else return null;
|
||||
}
|
||||
if (root.getAxisCoordinate() < node.point.getCoordinate(root.getAxis())) root.left = delete(root.left, node);
|
||||
else root.right = delete(root.right, node);
|
||||
if (
|
||||
root.getAxisCoordinate() < node.point.getCoordinate(root.getAxis())
|
||||
) root.left = delete(root.left, node); else root.right =
|
||||
delete(root.right, node);
|
||||
return root;
|
||||
}
|
||||
|
||||
@ -379,7 +416,6 @@ public class KDTree {
|
||||
return findNearest(root, point, root).point;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Finds the nearest point in a subtree to the given point.
|
||||
*
|
||||
@ -391,11 +427,17 @@ public class KDTree {
|
||||
if (root == null) return nearest;
|
||||
if (root.point.equals(point)) return root;
|
||||
int distance = Point.comparableDistance(root.point, point);
|
||||
int distanceExceptAxis = Point.comparableDistanceExceptAxis(root.point, point, root.getAxis());
|
||||
if (distance < Point.comparableDistance(nearest.point, point)) nearest = root;
|
||||
int distanceExceptAxis = Point.comparableDistanceExceptAxis(
|
||||
root.point,
|
||||
point,
|
||||
root.getAxis()
|
||||
);
|
||||
if (distance < Point.comparableDistance(nearest.point, point)) nearest =
|
||||
root;
|
||||
nearest = findNearest(root.getNearChild(point), point, nearest);
|
||||
if (distanceExceptAxis < Point.comparableDistance(nearest.point, point))
|
||||
nearest = findNearest(root.getFarChild(point), point, nearest);
|
||||
if (
|
||||
distanceExceptAxis < Point.comparableDistance(nearest.point, point)
|
||||
) nearest = findNearest(root.getFarChild(point), point, nearest);
|
||||
return nearest;
|
||||
}
|
||||
}
|
||||
|
@ -8,7 +8,6 @@ public class LCA {
|
||||
private static Scanner scanner = new Scanner(System.in);
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
//The adjacency list representation of a tree:
|
||||
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
|
||||
|
||||
@ -22,7 +21,6 @@ public class LCA {
|
||||
//Storing the given tree as an adjacency list
|
||||
int to, from;
|
||||
for (int i = 0; i < e; i++) {
|
||||
|
||||
to = scanner.nextInt();
|
||||
from = scanner.nextInt();
|
||||
|
||||
@ -44,7 +42,6 @@ public class LCA {
|
||||
|
||||
//Outputting the LCA
|
||||
System.out.println(getLCA(v1, v2, depth, parent));
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
@ -56,7 +53,13 @@ public class LCA {
|
||||
* @param parent An array to store parents of all vertices
|
||||
* @param depth An array to store depth of all vertices
|
||||
*/
|
||||
private static void dfs(ArrayList<ArrayList<Integer>> adj, int s, int p, int[] parent, int[] depth) {
|
||||
private static void dfs(
|
||||
ArrayList<ArrayList<Integer>> adj,
|
||||
int s,
|
||||
int p,
|
||||
int[] parent,
|
||||
int[] depth
|
||||
) {
|
||||
for (int adjacent : adj.get(s)) {
|
||||
if (adjacent != p) {
|
||||
parent[adjacent] = s;
|
||||
@ -94,7 +97,6 @@ public class LCA {
|
||||
return v1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Input:
|
||||
* 10
|
||||
|
@ -1,6 +1,7 @@
|
||||
package com.thealgorithms.datastructures.trees;
|
||||
|
||||
public class LazySegmentTree {
|
||||
|
||||
/**
|
||||
* Lazy Segment Tree
|
||||
*
|
||||
@ -8,10 +9,12 @@ public class LazySegmentTree {
|
||||
* <a href="https://www.geeksforgeeks.org/lazy-propagation-in-segment-tree/">
|
||||
*/
|
||||
static class Node {
|
||||
|
||||
private final int start, end; // start and end of the segment represented by this node
|
||||
private int value; // value is the sum of all elements in the range [start, end)
|
||||
private int lazy; // lazied value that should be added to children nodes
|
||||
Node left, right; // left and right children
|
||||
|
||||
public Node(int start, int end, int value) {
|
||||
this.start = start;
|
||||
this.end = end;
|
||||
@ -50,7 +53,11 @@ public class LazySegmentTree {
|
||||
static Node merge(Node left, Node right) {
|
||||
if (left == null) return right;
|
||||
if (right == null) return left;
|
||||
Node result = new Node(left.start, right.end, left.value + right.value);
|
||||
Node result = new Node(
|
||||
left.start,
|
||||
right.end,
|
||||
left.value + right.value
|
||||
);
|
||||
result.left = left;
|
||||
result.right = right;
|
||||
return result;
|
||||
@ -124,7 +131,10 @@ public class LazySegmentTree {
|
||||
if (left <= curr.start && curr.end <= right) return curr;
|
||||
if (left >= curr.end || right <= curr.start) return null;
|
||||
curr.shift();
|
||||
return Node.merge(getRange(left, right, curr.left), getRange(left, right, curr.right));
|
||||
return Node.merge(
|
||||
getRange(left, right, curr.left),
|
||||
getRange(left, right, curr.right)
|
||||
);
|
||||
}
|
||||
|
||||
public int getRange(int left, int right) {
|
||||
|
@ -25,7 +25,6 @@ public class LevelOrderTraversalQueue {
|
||||
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 */
|
||||
|
@ -6,6 +6,7 @@ import java.util.Queue;
|
||||
|
||||
// Class for a tree node
|
||||
class TreeNode {
|
||||
|
||||
// Members
|
||||
|
||||
int key;
|
||||
|
@ -29,7 +29,13 @@ public class RedBlackBST {
|
||||
}
|
||||
printTree(node.left);
|
||||
System.out.print(
|
||||
((node.color == R) ? " R " : " B ") + "Key: " + node.key + " Parent: " + node.p.key + "\n");
|
||||
((node.color == R) ? " R " : " B ") +
|
||||
"Key: " +
|
||||
node.key +
|
||||
" Parent: " +
|
||||
node.p.key +
|
||||
"\n"
|
||||
);
|
||||
printTree(node.right);
|
||||
}
|
||||
|
||||
@ -38,7 +44,13 @@ public class RedBlackBST {
|
||||
return;
|
||||
}
|
||||
System.out.print(
|
||||
((node.color == R) ? " R " : " B ") + "Key: " + node.key + " Parent: " + node.p.key + "\n");
|
||||
((node.color == R) ? " R " : " B ") +
|
||||
"Key: " +
|
||||
node.key +
|
||||
" Parent: " +
|
||||
node.p.key +
|
||||
"\n"
|
||||
);
|
||||
printTreepre(node.left);
|
||||
printTreepre(node.right);
|
||||
}
|
||||
|
@ -26,14 +26,21 @@ public class SegmentTree {
|
||||
}
|
||||
|
||||
int mid = start + (end - start) / 2;
|
||||
this.seg_t[index] = constructTree(arr, start, mid, index * 2 + 1)
|
||||
+ constructTree(arr, mid + 1, end, index * 2 + 2);
|
||||
this.seg_t[index] =
|
||||
constructTree(arr, start, mid, index * 2 + 1) +
|
||||
constructTree(arr, mid + 1, end, index * 2 + 2);
|
||||
return this.seg_t[index];
|
||||
}
|
||||
|
||||
/* A function which will update the value at a index i. This will be called by the
|
||||
update function internally*/
|
||||
private void updateTree(int start, int end, int index, int diff, int seg_index) {
|
||||
private void updateTree(
|
||||
int start,
|
||||
int end,
|
||||
int index,
|
||||
int diff,
|
||||
int seg_index
|
||||
) {
|
||||
if (index < start || index > end) {
|
||||
return;
|
||||
}
|
||||
@ -58,7 +65,13 @@ public class SegmentTree {
|
||||
}
|
||||
|
||||
/* A function to get the sum of the elements from index l to index r. This will be called internally*/
|
||||
private int getSumTree(int start, int end, int q_start, int q_end, int seg_index) {
|
||||
private int getSumTree(
|
||||
int start,
|
||||
int end,
|
||||
int q_start,
|
||||
int q_end,
|
||||
int seg_index
|
||||
) {
|
||||
if (q_start <= start && q_end >= end) {
|
||||
return this.seg_t[seg_index];
|
||||
}
|
||||
@ -68,7 +81,10 @@ public class SegmentTree {
|
||||
}
|
||||
|
||||
int mid = start + (end - start) / 2;
|
||||
return getSumTree(start, mid, q_start, q_end, seg_index * 2 + 1) + getSumTree(mid + 1, end, q_start, q_end, seg_index * 2 + 2);
|
||||
return (
|
||||
getSumTree(start, mid, q_start, q_end, seg_index * 2 + 1) +
|
||||
getSumTree(mid + 1, end, q_start, q_end, seg_index * 2 + 2)
|
||||
);
|
||||
}
|
||||
|
||||
/* A function to query the sum of the subarray [start...end]*/
|
||||
|
@ -1,6 +1,5 @@
|
||||
package com.thealgorithms.datastructures.trees;
|
||||
|
||||
|
||||
/* Author : Suraj Kumar
|
||||
Github : https://github.com/skmodi649
|
||||
*/
|
||||
@ -20,13 +19,14 @@ package com.thealgorithms.datastructures.trees;
|
||||
Step 6: STOP
|
||||
*/
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
// Using auxiliary array to find the random node in a given binary tree
|
||||
|
||||
public class TreeRandomNode {
|
||||
|
||||
private class Node {
|
||||
|
||||
int item;
|
||||
Node left, right;
|
||||
|
||||
@ -70,26 +70,20 @@ public class TreeRandomNode {
|
||||
// displaying the value at the generated index
|
||||
int random = list.get(b);
|
||||
System.out.println("Random Node : " + random);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* Explanation of the Approach :
|
||||
(a) Form the required binary tree
|
||||
(b) Now use the inOrder() method to get the nodes in inOrder fashion and also store them in the given arraylist 'list'
|
||||
(c) Using the getRandom() method generate a random number between 0 to n-1, then get the value at the generated random number
|
||||
from the arraylist using get() method and finally display the result.
|
||||
*/
|
||||
|
||||
|
||||
/* OUTPUT :
|
||||
First output :
|
||||
Random Node : 15
|
||||
Second output :
|
||||
Random Node : 99
|
||||
*/
|
||||
|
||||
/* Time Complexity : O(n)
|
||||
Auxiliary Space Complexity : O(1)
|
||||
*/
|
||||
|
@ -18,7 +18,7 @@ public class ValidBSTOrNot {
|
||||
/* 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
|
||||
/* returns true if given search tree is binary
|
||||
search tree (efficient version) */
|
||||
boolean isBST(Node root) {
|
||||
return isBSTUtil(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
|
||||
@ -40,6 +40,9 @@ public class ValidBSTOrNot {
|
||||
/* 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));
|
||||
return (
|
||||
isBSTUtil(node.left, min, node.data - 1) &&
|
||||
isBSTUtil(node.right, node.data + 1, max)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -60,7 +60,6 @@ public class VerticalOrderTraversal {
|
||||
index.offer(0);
|
||||
|
||||
while (!queue.isEmpty()) {
|
||||
|
||||
if (queue.peek().left != null) {
|
||||
/*Adding the left Node if it is not null
|
||||
and its index by subtracting 1 from it's
|
||||
|
@ -42,10 +42,8 @@ class Main {
|
||||
// Go right
|
||||
return nearestRightKey(root.right, x0);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class NRKTree {
|
||||
|
Reference in New Issue
Block a user