Sorry in advance for all the code provided, because I am unsure where the problem may be, I am adding the whole thing.
I am having trouble getting my program to output anything (just blank space). A great deal of this code comes straight from our book and what isn't is also from previous (yet similar) programs that I have gotten to work. I have been mainly focusing on the levelOrder and insert methods, though I'm thinking it may be the latter.
import java.util.Scanner;
import java.lang.*;
public class AVLTree {
private static class AvlNode {
int key;
AvlNode left;
AvlNode right;
int height; //height difference between right and left subtrees at node
AvlNode(int x) {
key = x;
left = right = null;
height = 0;
}
AvlNode( int x, AvlNode l, AvlNode r) {
key = x;
left = l;
right = r;
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean keepRunning = true;
while (keepRunning) {
System.out.print(">> Enter choice [1-7] from menu below: \n");
System.out.println("\t 1) Insert node");
System.out.println("\t 2) Remove node");
System.out.println("\t 3) Print level order");
System.out.println("\t 4) Exit program ");
int choice = input.nextInt();
int value;
switch (choice)
{
case 1:
System.out.print("Enter element to insert: ");
value = input.nextInt();
insert(value, root);
break;
case 2:
System.out.print("Enter element to remove: ");
value = input.nextInt();
remove(value);
break;
case 3:
levelOrder();
System.out.println("");
break;
case 4:
keepRunning = false;
break;
default:
System.out.println("Invalid Choice!");
keepRunning = false;
}
}
}
private static AvlNode root;
public AvlNode getroot() {
return root;
}
private static int height(AvlNode t) {
if(t == null) {
return 1;
}
else
return t.height;
}
private static final int ALLOWED_IMBALANCE = 1;
private static AvlNode balance(AvlNode t) {
if (t == null) {
return t;
}
if (height(t.left) - height(t.right) > ALLOWED_IMBALANCE) {
if (height(t.left.left) >= height(t.left.right)) {
t = singleRotateLL(t);
} else {
t = doubleRotateLR(t);
}
} else {
if (height(t.right) - height(t.left) > ALLOWED_IMBALANCE) {
if (height(t.right.right) >= height(t.right.left)) {
t = singleRotateRL(t);
} else {
t = doubleRotateRL(t);
}
}
}
t.height = Math.max(height(t.left), height(t.right)) + 1;
return t;
}
//public methods for insert, remove, findMin, findMax, find....
//The find function will not require modification because they do not change the structure of the tree
private static AvlNode singleRotateLL(AvlNode k2) {
AvlNode k1 = k2.left; //next make "poiner" adjustments for the LL rotate operation
k2.left = k1.right;
k1.right = k2;
k2.height = Math.max(height(k2.left), height(k2.right)) + 1;
k1.height = Math.max(height(k1.left), height(k1.right)) + 1;
return k1;
}
private static AvlNode doubleRotateLR(AvlNode k3) {
AvlNode k1 = k3.left; //next make "poiner" adjustments for the LL rotate operation
AvlNode k2 = k1.right;
k1.right = k2.left;
k3.left = k2.right;
k2.left = k1;
k2.right = k3;
k1.height = Math.max(height(k1.left), height(k1.right)) + 1;
k2.height = Math.max(height(k2.left), height(k2.right)) + 1;
k3.height = Math.max(height(k3.left), height(k3.right)) + 1;
return k2;
}
private static AvlNode singleRotateRL(AvlNode k2) {
AvlNode k1 = k2.right; //next make "poiner" adjustments for the LL rotate operation
k2.right = k1.left;
k1.left = k2;
k2.height = Math.max(height(k2.right), height(k2.left)) + 1;
k1.height = Math.max(height(k1.right), height(k1.left)) + 1;
return k1;
}
private static AvlNode doubleRotateRL(AvlNode k3) {
AvlNode k1 = k3.right; //next make "poiner" adjustments for the LL rotate operation
AvlNode k2 = k1.left;
k1.left = k2.right;
k3.right = k2.left;
k2.right = k1;
k2.left = k3;
k1.height = Math.max(height(k1.right), height(k1.left)) + 1;
k2.height = Math.max(height(k2.right), height(k2.left)) + 1;
k3.height = Math.max(height(k3.right), height(k3.left)) + 1;
return k2;
}
private static AvlNode insert(int x, AvlNode t) {
if(t == null)
return new AvlNode(x, null, null);
int compareResult = Integer.compare(x, t.key);
if(compareResult < 0) {
t.left = insert(x, t.left);
}
else if(compareResult > 0) {
t.right = insert(x, t.right);
}
else; // duplicate, do nothing
return balance(t);
}
public int findMin() {
return findMin(root).key;
}
private static AvlNode findMin(AvlNode t) {
if (t == null) {
return null;
}
if (t.left == null) {
return t;
}
return findMin(t.left);
}
public static void remove(int x) {
remove(x, root);
}
private static AvlNode remove(int x, AvlNode t) {
if (t == null) {
return t;
}
int compareResult = Integer.compare(x, t.key);
if (compareResult < 0) {
t.left = remove(x, t.left);
}
else if (compareResult > 0) {
t.right = remove(x, t.right);
}
else if ((t.left != null) && (t.right != null)) {
t.key = findMin(t.right).key;
t.right = remove(t.key, t.right);
}
else {
t = (t.left != null) ? t.left : t.right;
}
return balance(t);
}
private static void levelOrder() { //prints the level order traversal of the tree
int h = height(root);
for(int i = 1; i <= h; i++) {
printLevel(root, i);
}
}
private static void printLevel(AvlNode t, int level) {
if(t == null) {
return;
}
if(level == 1) {
System.out.print(t.key + " ");
}
else if(level > 1) {
printLevel(t.left, level - 1);
printLevel(t.right, level - 1);
}
}
}
You had to do two changes, one is to initialize root and the first time, and the second one is to change the height accordingly.
Just change the following class & function :
private static AvlNode insert(int x, AvlNode t) {
if (t == null && root==null)
return (root = new AvlNode(x, null, null));
else if (t==null) {
return new AvlNode(x, null, null);
}
t.height++;
int compareResult = Integer.compare(x, t.key);
if (compareResult < 0) {
t.left = insert(x, t.left);
} else if (compareResult > 0) {
t.right = insert(x, t.right);
} else {
t.height--;
}
return balance(t);
}
private static class AvlNode {
int key;
AvlNode left;
AvlNode right;
int height=0;
AvlNode(int x, AvlNode l, AvlNode r) {
key = x;
left = l;
right = r;
this.height++;
}
}
Related
if(t == null) //If search is complete and no element is found
{
return null;
}
else
{
if(x < t.data)
t.left = delete(t.left, x);
else if(x > t.data)
t.right = delete(t.right, x);
else if(t.left != null && t.right != null)
{
TreeNode temp = findMax(t.left);
t.data = temp.data;
t.left = delete(t.left, temp.data);
}
else
{
TreeNode child = null;
if(t.left == null)
child = t.right;
if(t.right == null)
child = t.left;
return child;
}
t.height = Math.max(height(t.left), height(t.right)) + 1; //Update the height of TreeNodes
t = balanceTree(t);
return t;
}
private TreeNode balanceTree(TreeNode t)
{
if(getBalance(t) > 1)
{
if (getBalance(t.left) >= 0)
return singleRotateLeftToRight(t);
else
return doubleRotateLeftToRight(t);
}
else
{
if (getBalance(t) < -1)
{
if (getBalance(t.right) <= 0)
return singleRotateRightToLeft(t);
else
return doubleRotateRightToLeft(t);
}
}
return t;
}
public static void main(String[] args)
{
AVLTree v = new AVLTree();
v.insert(50);
v.insert(40);
v.insert(35);
v.insert(37);
v.insert(34);
v.insert(55);
v.insert(60);
v.insert(54);
v.insert(53);
v.insert(52);
v.insert(5);
v.insert(4);
v.insert(3);
v.delete(40);
v.delete(35);
v.delete(37);
v.delete(53);
v.delete(60);
v.insert(2);
v.insert(6);
v.delete(34);
v.delete(6);
v.delete(50);
v.delete(4);
v.delete(3);
v.delete(2);
}
private TreeNode singleRotateLeftToRight(TreeNode k1) // (Utility Method) Performs single rotation of a TreeNode from left to right
{
TreeNode k2 = k1.left;
k1.left = k2.right;
k2.right = k1;
k1.height = Math.max(height(k1.left), height(k1.right)) + 1;
k2.height = Math.max(height(k2.left), height(k2.right)) + 1;
return k2;
}
private TreeNode singleRotateRightToLeft(TreeNode k1) //(Utility Method) Performs single rotation of a TreeNode from right to left
{
TreeNode k2 = k1.right;
k1.right = k2.left;
k2.left = k1;
k1.height = Math.max(height(k1.left), height(k1.right)) + 1;
k2.height = Math.max(height(k2.left), height(k2.right)) + 1;
return k2;
}
private TreeNode doubleRotateLeftToRight(TreeNode k1) //(Utility Method) Performs double rotation of a TreeNode from left to right
{
k1.left = singleRotateRightToLeft(k1.left);
return singleRotateLeftToRight(k1);
}
private TreeNode doubleRotateRightToLeft(TreeNode k1) //(Utility Method) Performs double rotation of a TreeNode from right to left
{
k1.right = singleRotateLeftToRight(k1.right);
return singleRotateRightToLeft(k1);
}
private int getBalance(TreeNode t) { //Returns the difference between the height of the left TreeNode and right TreeNode (utility method)
if(t == null)
return -1;
return height(t.left) - height(t.right);
}
the insertion code works fine but when it comes to deletion I get problems its like some tree nodes disappear and I'm sure that the rotation codes are fine but whats wrong with my code when I delete the tree node with 2 the nodes with 54 and 55 are missing and I'm pretty sure there are no problems with the deletion but it should be with the rotations or maybe I'm balancing the wrong nodes I don't know.
The error I believe starts on line 102: int treeDepth(Node Node) because when I run the code with a regular while loop with a count, it runs and displays a tree. But as soon as I change the while condition to while (treeDepth(this.root) <= 5) it runs but displays nothing, and I get no errors. Trying to make it so the tree that is created doesn't have a depth larger than 5.
import java.io.*;
import java.util.*;
class Node {
int value;
Node left;
Node right;
Node(int value) {
this.value = value;
right = null;
left = null;
}
}
public class treeStructureBinary{
Node root;
public static void main(String[] args) {
treeStructureBinary bn =new treeStructureBinary();
bn.appMain(args);
}
void appMain(String[] args) {
createBinaryTree();
}
private Node addRecursive(Node current, int value) {
if (current == null) {
return new Node(value);
}
if (value < current.value) {
current.left = addRecursive(current.left, value);
} else if (value > current.value) {
current.right = addRecursive(current.right, value);
} else {
return current;
}
return current;
}
public void add(int value) {
this.root = addRecursive(this.root, value);
}
public treeStructureBinary createBinaryTree() {
treeStructureBinary bt = new treeStructureBinary();
int [] array = new int[89];
int counter = 0;
boolean check = true;
while (treeDepth(this.root) <= 5)
{
Random rand = new Random();
int n = rand.nextInt(89) + 10;
for(int z = 0; z <= counter; z++)
{
if ( n == array[z])
{
check = false;
break;
}
}
if (check == true)
{
bt.add(n);
array[counter] = n;
counter++;
}
check = true;
}
bt.traverseLevelOrder();
return bt;
}
public void traverseLevelOrder() {
if (this.root == null) {
return;
}
Queue<Node> nodes = new LinkedList<>();
nodes.add(this.root);
while (!nodes.isEmpty()) {
Node node = nodes.remove();
System.out.print(" " + node.value);
if (node.left != null) {
nodes.add(node.left);
}
if (node.right != null) {
nodes.add(node.right);
}
}
}
int treeDepth(Node Node){
if (Node == null) {
return 0;
}else {
int lDepth = treeDepth(Node.left);
int rDepth = treeDepth(Node.right);
if (lDepth > rDepth) {
System.out.println("lDepth" + "\n");
return (lDepth + 1);
}else {
System.out.println("rDepth" + "\n");
return (rDepth + 1);
}
}
}
}
I think your addRecursive never actually adds the node to the tree--or always adds it? Anyway it looks funky. I'd focus on that for a bit.
This code in particular:
if (value < current.value) {
current.left = addRecursive(current.left, value);
} else if (value > current.value) {
current.right = addRecursive(current.right, value);
} else {
return current;
}
always forces an assign (even if it's not a leaf) and the final else will only execute when value == current.value which is probably not what you want.
I don't really want to go much further because it looks homeworky and you'll gain more figuring it out yourself.
It might work anyway (You just may be re-assigning every node at every level) but I'm not sure without running it.
Anyway, if this is a homework assignment I'd really like to commend you on your style, it's one of the best I've seen posted here for a homework-like question.
Main problem here is that you are working on two different trees.
First you create one tree in main function:
public static void main(String[] args) {
treeStructureBinary bn =new treeStructureBinary();
bn.appMain(args);
}
Then you create another one in createBinaryTree method:
public SthApplication createBinaryTree() {
treeStructureBinary bt = new treeStructureBinary();
See, you used new keyword twice, so there will be two objects.
Later in your app you refer to this.root (which is the one from main), but some methods use local variable bt.
In example, treeDepth(this.root) operates on different tree then the bt.add(n), so it goes into infinite loop.
If you solve that problem, you will know how to finish the rest.
Thanks guys I figured it out!
import java.io.*;
import java.util.*;
class Node {
int value;
int balancefactor;
int nodex;
Node left;
Node right;
Node(int value, int balancefactor, int nodex) {
this.value = value;
this.balancefactor = balancefactor;
this.nodex = nodex;
this.right = null;
this.left = null;
}
}
public class treeStructureBinary{
Node root;
public static void main(String[] args) {
treeStructureBinary bn =new treeStructureBinary();
bn.appMain(args);
}
void appMain(String[] args) {
int count = args.length;
if (count >1) {
count = 1;
}
String [] cmdln = {""};
for (int i=0;i<count;i++) {
cmdln[i]=args[i];
}
if (cmdln[0].equals("BT")){
createBinaryTree();
} else if (cmdln[0].equals("AVL")) {
} else {
System.out.println("Please enter BT or AVL to choose the type of
tree.");
}
}
private Node addRecursive(Node current, int value, int balancefactor, int
nodex) {
if (current == null) {
return new Node(value, balancefactor, nodex);
} if (value < current.value) {
balancefactor++;
nodex=(nodex*2);
current.left = addRecursive(current.left, value, balancefactor,
nodex);
} else if (value > current.value) {
balancefactor++;
nodex=(nodex*2)+1;
current.right = addRecursive(current.right, value, balancefactor,
nodex);
} else {
return current;
}
return current;
}
public void add(int value) {
int balancefactor=1;
int nodex=0;
this.root = addRecursive(this.root, value, balancefactor, nodex);
}
public treeStructureBinary createBinaryTree() {
treeStructureBinary bt = new treeStructureBinary();
int [] array = new int[89];
int counter = 0;
boolean check = true;
int temp = 0;
while (temp < 5) {
Random rand = new Random();
int n = rand.nextInt(89) + 10;
for(int z = 0; z <= counter; z++) {
if ( n == array[z]) {
check = false;
break;
}
}
if (check == true) {
bt.add(n);
array[counter] = n;
counter++;
}
check = true;
temp = bt.treeDepth();
}
bt.traverseLevelOrder();
Scanner reader =new Scanner(System.in);
System.out.println("\n\nEnter a number to delete or 0 to exit");
int input = reader.nextInt();
Boolean isMatch = true;
while (input!=0) {
for(int p = 0; p < counter; p++)
{
//System.out.println(array[p]);
if (input != array[p])
{
isMatch = false;
}
else
{
isMatch = true;
array[p] = 0;
break;
}
}
if (isMatch == false )
{
System.out.println("Error, number not found.");
}
bt.nodeDelete(input);
bt.traverseLevelOrder();
System.out.println("\n\nEnter a number to delete or 0 to exit");
input = reader.nextInt();
}
return bt;
}
public void traverseLevelOrder() {
int count = 0;
int outer = 31;
int inner = 30;
int lastnode= 0;
int check = 0;
if (this.root == null) {
return;
}
Queue<Node> nodes = new LinkedList<>();
nodes.add(this.root);
while (!nodes.isEmpty()) {
Node node = nodes.remove();
if (count < node.balancefactor) {
System.out.print("\n");
for (int i=0; i<outer; i++) {
System.out.print(" ");
}
inner=outer;
outer=outer/2;
count++;
lastnode=0;
check=0;
}
check=((node.nodex-lastnode));
for (int i=0; i<(inner*check*2);i++) {
System.out.print(" ");
}
if (check >1) {
for (int j=0;j<check;j++) {
System.out.print(" ");
}
}
lastnode=node.nodex;
System.out.print(node.value);
if (node.left != null) {
nodes.add(node.left);
}
if (node.right != null) {
if (node.right==null &&lastnode == 0) {
if (count==5) {
break;
}
System.out.print(" ");
}
nodes.add(node.right);
}
}
}
int treeDepth(){
int temp = treeDepthRecursive(this.root);
return temp;
}
int treeDepthRecursive(Node current) {
if (current == null) {
return 0;
} else {
int lDepth = treeDepthRecursive(current.left);
int rDepth = treeDepthRecursive(current.right);
if (lDepth > rDepth) {
return (lDepth + 1);
} else {
return (rDepth + 1);
}
}
}
public void nodeDelete(int value) {
nodeDeleteRecursive(root, value);
}
public Node nodeDeleteRecursive(Node current, int value) {
if (current == null) {
return null;
}
if (value == current.value) {
if (current.left ==null && current.right==null) {
return null;
}
if (current.right==null) {
return current.left;
}
if (current.left==null) {
return current.right;
}
int sValue = findSmall(current.right);
current.value = sValue;
current.right = nodeDeleteRecursive(current.right, sValue);
return current;
}
if (value < current.value) {
current.left = nodeDeleteRecursive(current.left, value);
return current;
}
current.right =nodeDeleteRecursive(current.right, value);
return current;
}
public int findSmall(Node root) {
return root.left == null?(root.value):(findSmall(root.left));
}
}
I am working on a Binary Search Tree algorithm (called BST in the code) and whenever I run the program it just keeps running for a long time. I know this means that there is an infinite loop but I can't figure out what/where is the problem (I've been trying for a while). I've had this problem once before and never figured that out either. If anyone could help find out where the loop is, what to change it to and also explain why it causes it I would be extremely grateful for the knowledge as it would also help me for future endeavors. Here is the code:
import java.util.Queue;
import java.util.ArrayDeque;
public class BST<Key extends Comparable<Key>, Value> {
private Node root; // root of BST
private class Node {
private Key key; // sorted by key
private Value val; // associated data
private Node left, right; // left and right subtrees
private int N; // number of nodes in subtree
public Node(Key key, Value val, int N) {
this.key = key;
this.val = val;
this.N = N;
}
}
// is the symbol table empty?
public boolean isEmpty() {
return size() == 0;
}
// return number of key-value pairs in BST
public int size() {
return size(root);
}
// return number of key-value pairs in BST rooted at x
private int size(Node x) {
if (x == null) return 0;
else return x.N;
}
/***********************************************************************
* Search BST for given key, and return associated value if found,
* return null if not found
***********************************************************************/
// does there exist a key-value pair with given key?
public boolean contains(Key key) {
return get(key) != null;
}
// return value associated with the given key, or null if no such key exists
public Value get(Key key) {
return get(root, key);
}
private Value get(Node x, Key key) {
if (x == null) return null;
int cmp = key.compareTo(x.key);
if (cmp < 0) return get(x.left, key);
else if (cmp > 0) return get(x.right, key);
else return x.val;
}
/***********************************************************************
* Insert key-value pair into BST
* If key already exists, update with new value
***********************************************************************/
public void put(Key key, Value val) {
if (val == null) { delete(key); return; }
root = put(root, key, val);
assert check();
}
private Node put(Node x, Key key, Value val) {
if (x == null) return new Node(key, val, 1);
int cmp = key.compareTo(x.key);
if (cmp < 0) x.left = put(x.left, key, val);
else if (cmp > 0) x.right = put(x.right, key, val);
else x.val = val;
x.N = 1 + size(x.left) + size(x.right);
return x;
}
/***********************************************************************
* Delete
***********************************************************************/
public void deleteMin() {
if (isEmpty()) throw new RuntimeException("Symbol table underflow");
root = deleteMin(root);
assert check();
}
private Node deleteMin(Node x) {
if (x.left == null) return x.right;
x.left = deleteMin(x.left);
x.N = size(x.left) + size(x.right) + 1;
return x;
}
public void deleteMax() {
if (isEmpty()) throw new RuntimeException("Symbol table underflow");
root = deleteMax(root);
assert check();
}
private Node deleteMax(Node x) {
if (x.right == null) return x.left;
x.right = deleteMax(x.right);
x.N = size(x.left) + size(x.right) + 1;
return x;
}
public void delete(Key key) {
root = delete(root, key);
assert check();
}
private Node delete(Node x, Key key) {
if (x == null) return null;
int cmp = key.compareTo(x.key);
if (cmp < 0) x.left = delete(x.left, key);
else if (cmp > 0) x.right = delete(x.right, key);
else {
if (x.right == null) return x.left;
if (x.left == null) return x.right;
Node t = x;
x = min(t.right);
x.right = deleteMin(t.right);
x.left = t.left;
}
x.N = size(x.left) + size(x.right) + 1;
return x;
}
/***********************************************************************
* Min, max, floor, and ceiling
***********************************************************************/
public Key min() {
if (isEmpty()) return null;
return min(root).key;
}
private Node min(Node x) {
if (x.left == null) return x;
else return min(x.left);
}
public Key max() {
if (isEmpty()) return null;
return max(root).key;
}
private Node max(Node x) {
if (x.right == null) return x;
else return max(x.right);
}
public Key floor(Key key) {
Node x = floor(root, key);
if (x == null) return null;
else return x.key;
}
private Node floor(Node x, Key key) {
if (x == null) return null;
int cmp = key.compareTo(x.key);
if (cmp == 0) return x;
if (cmp < 0) return floor(x.left, key);
Node t = floor(x.right, key);
if (t != null) return t;
else return x;
}
public Key ceiling(Key key) {
Node x = ceiling(root, key);
if (x == null) return null;
else return x.key;
}
private Node ceiling(Node x, Key key) {
if (x == null) return null;
int cmp = key.compareTo(x.key);
if (cmp == 0) return x;
if (cmp < 0) {
Node t = ceiling(x.left, key);
if (t != null) return t;
else return x;
}
return ceiling(x.right, key);
}
/***********************************************************************
* Rank and selection
***********************************************************************/
public Key select(int k) {
if (k < 0 || k >= size()) return null;
Node x = select(root, k);
return x.key;
}
// Return key of rank k.
private Node select(Node x, int k) {
if (x == null) return null;
int t = size(x.left);
if (t > k) return select(x.left, k);
else if (t < k) return select(x.right, k-t-1);
else return x;
}
public int rank(Key key) {
return rank(key, root);
}
// Number of keys in the subtree less than x.key.
private int rank(Key key, Node x) {
if (x == null) return 0;
int cmp = key.compareTo(x.key);
if (cmp < 0) return rank(key, x.left);
else if (cmp > 0) return 1 + size(x.left) + rank(key, x.right);
else return size(x.left);
}
/***********************************************************************
* Range count and range search.
***********************************************************************/
public Iterable<Key> keys() {
return keys(min(), max());
}
public Iterable<Key> keys(Key lo, Key hi) {
Queue<Key> queue = new ArrayDeque<Key>();
keys(root, queue, lo, hi);
return queue;
}
private void keys(Node x, Queue<Key> queue, Key lo, Key hi) {
if (x == null) return;
int cmplo = lo.compareTo(x.key);
int cmphi = hi.compareTo(x.key);
if (cmplo < 0) keys(x.left, queue, lo, hi);
if (cmplo <= 0 && cmphi >= 0) queue.offer(x.key);
if (cmphi > 0) keys(x.right, queue, lo, hi);
}
public int size(Key lo, Key hi) {
if (lo.compareTo(hi) > 0) return 0;
if (contains(hi)) return rank(hi) - rank(lo) + 1;
else return rank(hi) - rank(lo);
}
// height of this BST (one-node tree has height 0)
public int height() { return height(root); }
private int height(Node x) {
if (x == null) return -1;
return 1 + Math.max(height(x.left), height(x.right));
}
/*************************************************************************
* Check integrity of BST data structure
*************************************************************************/
private boolean check() {
if (!isBST()) System.out.println("Not in symmetric order");
if (!isSizeConsistent()) System.out.println("Subtree counts not consistent");
if (!isRankConsistent()) System.out.println("Ranks not consistent");
return isBST() && isSizeConsistent() && isRankConsistent();
}
// does this binary tree satisfy symmetric order?
// Note: this test also ensures that data structure is a binary tree since order is strict
private boolean isBST() {
return isBST(root, null, null);
}
// is the tree rooted at x a BST with all keys strictly between min and max
// (if min or max is null, treat as empty constraint)
// Credit: Bob Dondero's elegant solution
private boolean isBST(Node x, Key min, Key max) {
if (x == null) return true;
if (min != null && x.key.compareTo(min) <= 0) return false;
if (max != null && x.key.compareTo(max) >= 0) return false;
return isBST(x.left, min, x.key) && isBST(x.right, x.key, max);
}
// are the size fields correct?
private boolean isSizeConsistent() { return isSizeConsistent(root); }
private boolean isSizeConsistent(Node x) {
if (x == null) return true;
if (x.N != size(x.left) + size(x.right) + 1) return false;
return isSizeConsistent(x.left) && isSizeConsistent(x.right);
}
// check that ranks are consistent
private boolean isRankConsistent() {
for (int i = 0; i < size(); i++)
if (i != rank(select(i))) return false;
for (Key key : keys())
if (key.compareTo(select(rank(key))) != 0) return false;
return true;
}
/*****************************************************************************
* Test client
*****************************************************************************/
public static void main(String[] args) {
BST<String, Integer> st = new BST<String, Integer>();
for (int i = 0; !System.out.equals(i); i++) {
String key = System.out.toString();
st.put(key, i);
}
for (String s : st.keys())
System.out.println(s + " " + st.get(s));
}
}
Thank you in advance to anyone who ofers help!
for (int i = 0; !System.out.equals(i); i++)
system out won't be ever equals an integer
I want to implement the Java AVL tree and to rotate the tree left and right. I am not getting this.
Can anybody by looking at the code below tell me how can I possibly rotate the tree left and right and then use fix up with those two functions to balance the AVL tree?
I hope someone here can guide me through this.
import java.util.Random;
import java.util.SortedSet;
import java.util.TreeSet;
public class AVLTree<T> extends
BinarySearchTree<AVLTree.Node<T>, T> implements SSet<T> {
Random rand;
public static class Node<T> extends BSTNode<Node<T>,T> {
int h; // the height of the node
}
public AVLTree() {
sampleNode = new Node<T>();
rand = new Random();
c = new DefaultComparator<T>();
}
public int height(Node<T> u) {
return (u == null) ? 0 : u.h;
}
public boolean add(T x) {
Node<T> u = new Node<T>();
u.x = x;
if (super.add(u)) {
for (Node<T> w = u; w != nil; w = w.parent) {
// walk back up to the root adjusting heights
w.h = Math.max(height(w.left), height(w.right)) + 1;
}
fixup(u);
return true;
}
return false;
}
public void splice(Node<T> u) {
Node<T> w = u.parent;
super.splice(u);
for (Node<T> z = u; z != nil; z = z.parent)
z.h = Math.max(height(z.left), height(z.right)) + 1;
fixup(w);
}
public void checkHeights(Node<T> u) {
if (u == nil) return;
checkHeights(u.left);
checkHeights(u.right);
if (height(u) != 1 + Math.max(height(u.left), height(u.right)))
throw new RuntimeException("Check heights shows incorrect heights");
int dif = height(u.left) - height(u.right);
if (dif < -1 || dif > 1)
throw new RuntimeException("Check heights found height difference of " + dif);
}
/**
* TODO: finish writing this method
* #param u
*/
public void fixup(Node<T> u) {
while (u != nil) {
int dif = height(u.left) - height(u.right);
if (dif > 1) {
// TODO: add code here to fix AVL condition
// on the path from u to the root, if necessary
} else if (dif < -1) {
// TODO: add code here to fix AVL condition
// on the path from u to the root, if necessary
}
u = u.parent;
}
}
public Node rotateLeft() {
return rotateLeft(u.parent);
}
public void rotateLeft(Node<T> u) {
// TODO: Recompute height values at u and u.parent
}
public void rotateRight(Node<T> u) {
// TODO: Recompute height values at u and u.parent
}
public static <T> T find(SortedSet<T> ss, T x) {
SortedSet<T> ts = ss.tailSet(x);
if (!ts.isEmpty()) {
return ts.first();
}
return null;
}
/**
* This just does some very basic correctness testing
* #param args
*/
public static void main(String[] args) {
AVLTree<Integer> t = new AVLTree<Integer>();
Random r = new Random(0);
System.out.print("Running AVL tests...");
int n = 1000;
for (int i = 0; i < n; i++) {
t.add(r.nextInt(2*n));
t.checkHeights(t.r);
}
for (int i = 0; i < n; i++) {
t.remove(r.nextInt(2*n));
t.checkHeights(t.r);
}
System.out.println("done");
t.clear();
System.out.print("Running correctness tests...");
n = 100000;
SortedSet<Integer> ss = new TreeSet<Integer>();
Random rand = new Random();
for (int i = 0; i < n; i++) {
Integer x = rand.nextInt(2*n);
boolean b1 = t.add(x);
boolean b2 = ss.add(x);
if (b1 != b2) {
throw new RuntimeException("Adding " + x + " gives " + b2
+ " in SortedSet and " + b1 + " in AVL Tree");
}
}
for (int i = 0; i < n; i++) {
Integer x = rand.nextInt(2*n);
Integer x1 = t.find(x);
Integer x2 = find(ss, x);
if (x1 != x2) {
throw new RuntimeException("Searching " + x + " gives " + x2
+ " in SortedSet and " + x1 + " in AVL Tree");
}
ss.headSet(x);
}
for (int i = 0; i < n; i++) {
Integer x = rand.nextInt(2*n);
boolean b1 = t.remove(x);
boolean b2 = ss.remove(x);
if (b1 != b2) {
throw new RuntimeException("Error (2): Removing " + x + " gives " + b2
+ " in SortedSet and " + b1 + " in AVL Tree");
}
}
for (int i = 0; i < n; i++) {
Integer x = rand.nextInt(2*n);
Integer x1 = t.find(x);
Integer x2 = find(ss, x);
if (x1 != x2) {
throw new RuntimeException("Error (3): Searching " + x + " gives " + x2
+ " in SortedSet and " + x1 + " in AVL Tree");
}
ss.headSet(x);
}
System.out.println("done");
}
}
Full AVL tree implementation:
public class AVLTree<T> {
private AVLNode<T> root;
private static class AVLNode<T> {
private T t;
private int height;
private AVLNode<T> left;
private AVLNode<T> right;
private AVLNode(T t) {
this.t = t;
height = 1;
}
}
public void insert(T value) {
root = insert(root, value);
}
private AVLNode<T> insert(AVLNode<T> n, T v) {
if (n == null) {
n = new AVLNode<T>(v);
return n;
} else {
int k = ((Comparable) n.t).compareTo(v);
if (k > 0) {
n.left = insert(n.left, v);
} else {
n.right = insert(n.right, v);
}
n.height = Math.max(height(n.left), height(n.right)) + 1;
int heightDiff = heightDiff(n);
if (heightDiff < -1) {
if (heightDiff(n.right) > 0) {
n.right = rightRotate(n.right);
return leftRotate(n);
} else {
return leftRotate(n);
}
} else if (heightDiff > 1) {
if (heightDiff(n.left) < 0) {
n.left = leftRotate(n.left);
return rightRotate(n);
} else {
return rightRotate(n);
}
} else;
}
return n;
}
private AVLNode<T> leftRotate(AVLNode<T> n) {
AVLNode<T> r = n.right;
n.right = r.left;
r.left = n;
n.height = Math.max(height(n.left), height(n.right)) + 1;
r.height = Math.max(height(r.left), height(r.right)) + 1;
return r;
}
private AVLNode<T> rightRotate(AVLNode<T> n) {
AVLNode<T> r = n.left;
n.left = r.right;
r.right = n;
n.height = Math.max(height(n.left), height(n.right)) + 1;
r.height = Math.max(height(r.left), height(r.right)) + 1;
return r;
}
private int heightDiff(AVLNode<T> a) {
if (a == null) {
return 0;
}
return height(a.left) - height(a.right);
}
private int height(AVLNode<T> a) {
if (a == null) {
return 0;
}
return a.height;
}
}
Here's a full implementation of AVL tree in Java
class Node {
int key;
Node left;
Node right;
int height;
Node(int value) {
key = value;
left = null;
right = null;
height = 1;
}
}
class AVLTree {
Node root;
int height(Node root) {
if (root == null)
return 0;
return root.height;
}
int findHeight() {
return height(root);
}
int findHeightFrom(int value) {
Node node = search(root, value);
if (node == null)
return -1;
return node.height;
}
Node search(Node root, int value) {
if (root == null)
return null;
else {
if (value == root.key)
return root;
else if (value < root.key)
return search(root.left, value);
else
return search(root.right, value);
}
}
boolean find(int value) {
Node node = search(root,value);
if (node == null)
return false;
return true;
}
int max(int one, int two) {
return (one > two) ? one : two;
}
Node rightRotate(Node root) {
Node rootLeftChild = root.left;
root.left = rootLeftChild.right;
rootLeftChild.right = root;
root.height = max(height(root.left), height(root.right)) + 1;
rootLeftChild.height = max(height(rootLeftChild.left), height(rootLeftChild.right)) + 1;
return rootLeftChild;
}
Node leftRotate(Node root) {
Node rootRightChild = root.right;
root.right = rootRightChild.left;
rootRightChild.left = root;
root.height = max(height(root.left), height(root.right)) + 1;
rootRightChild.height = max(height(rootRightChild.left), height(rootRightChild.right)) + 1;
return rootRightChild;
}
Node insertNode(Node root, int value) {
if (root == null)
root = new Node(value);
else {
if (value < root.key)
root.left = insertNode(root.left, value);
else
root.right = insertNode(root.right, value);
}
root.height = max(height(root.left), height(root.right)) + 1;
int balanceFactor = height(root.left) - height(root.right);
if (balanceFactor > 1) {
// either left-left case or left-right case
if (value < root.left.key) {
// left-left case
root = rightRotate(root);
} else {
// left-right case
root.left = leftRotate(root.left);
root = rightRotate(root);
}
} else if (balanceFactor < -1) {
// either right-right case or right-left case
if (value > root.right.key) {
// right-right case
root = leftRotate(root);
} else {
// right-left case
root.right = rightRotate(root.right);
root = leftRotate(root);
}
}
return root;
}
void insert(int value) {
root = insertNode(root, value);
}
void inorder(Node root) {
if (root != null) {
inorder(root.left);
System.out.print(root.key + " ");
inorder(root.right);
}
}
void inorderTraversal() {
inorder(root);
System.out.println();
}
void preorder(Node root) {
if (root != null) {
System.out.print(root.key + " ");
preorder(root.left);
preorder(root.right);
}
}
void preorderTraversal() {
preorder(root);
System.out.println();
}
}
public class AVLTreeExample {
public static void main(String[] args) {
AVLTree avl = new AVLTree();
avl.insert(10);
avl.insert(20);
avl.insert(30);
avl.insert(40);
avl.insert(50);
avl.insert(25);
System.out.print("Inorder Traversal : "); avl.inorderTraversal();
System.out.print("Preorder Traversal : "); avl.preorderTraversal();
System.out.println("Searching for 10 : " + avl.find(10));
System.out.println("Searching for 11 : " + avl.find(11));
System.out.println("Searching for 20 : " + avl.find(20));
System.out.println("Height of the tree : " + avl.findHeight());
System.out.println("Finding height from 10 : " + avl.findHeightFrom(10));
System.out.println("Finding height from 20 : " + avl.findHeightFrom(20));
System.out.println("Finding height from 25 : " + avl.findHeightFrom(25));
}
}
in order to rotate it right
you need to first check if the parent is not root
then if the parent is the right of the grand parent
if so, set the right of the grand parent to the child
else, set the left of the gran parent to the child
otherwise,
root is child
For an assignment, we were instructed to create a priority queue implemented via a binary heap, without using any built-in classes, and I have done so successfully by using an array to store the queued objects. However, I'm interested in learning how to implement another queue by using an actual tree structure, but in doing so I've run across a bit of a problem.
How would I keep track of the nodes on which I would perform insertion and deletion? I have tried using a linked list, which appends each node as it is inserted - new children are added starting from the first list node, and deleted from the opposite end. However, this falls apart when elements are rearranged in the tree, as children are added at the wrong position.
Edit: Perhaps I should clarify - I'm not sure how I would be able to find the last occupied and first unoccupied leaves. For example, I would always be able to tell the last inserted leaf, but if I were to delete it, how would I know which leaf to delete when I next remove the item? The same goes for inserting - how would I know which leaf to jump to next after the current leaf has both children accounted for?
A tree implementation of a binary heap uses a complete tree [or almost full tree: every level is full, except the deepest one].
You always 'know' which is the last occupied leaf - where you delete from [and modifying it is O(logn) after it changed so it is not a problem], and you always 'know' which is the first non-occupied leaf, in which you add elements to [and again, modifying it is also O(logn) after it changed].
The algorithm idea is simple:
insert: insert element to the first non-occupied leaf, and use heapify [sift up] to get this element to its correct place in the heap.
delete_min: replace the first element with the last occupied leaf, and remove the last occupied leaf. then, heapify [sift down] the heap.
EDIT: note that delete() can be done to any element, and not only the head, however - finding the element you want to replace with the last leaf will be O(n), which will make this op expensive. for this reason, the delete() method [besides the head], is usually not a part of the heap data structure.
I really wanted to do this for almost a decade.Finally sat down today and wrote it.Anyone who wants it can use it.I got inspired by Quora founder to relearn Heap.Apparently he was asked how would you find K near points in a set of n points in his Google phone screen.Apparently his answer was to use a Max Heap and to store K values and remove the maximum element after the size of the heap exceeds K.The approach is pretty simple and the worst case is nlog K which is better than n^2 in most sorting cases.Here is the code.
import java.util.ArrayList;
import java.util.List;
/**
* #author Harish R
*/
public class HeapPractise<T extends Comparable<T>> {
private List<T> heapList;
public List<T> getHeapList() {
return heapList;
}
public void setHeapList(List<T> heapList) {
this.heapList = heapList;
}
private int heapSize;
public HeapPractise() {
this.heapList = new ArrayList<>();
this.heapSize = heapList.size();
}
public void insert(T item) {
if (heapList.size() == 0) {
heapList.add(item);
} else {
siftUp(item);
}
}
public void siftUp(T item) {
heapList.add(item);
heapSize = heapList.size();
int currentIndex = heapSize - 1;
while (currentIndex > 0) {
int parentIndex = (int) Math.floor((currentIndex - 1) / 2);
T parentItem = heapList.get(parentIndex);
if (parentItem != null) {
if (item.compareTo(parentItem) > 0) {
heapList.set(parentIndex, item);
heapList.set(currentIndex, parentItem);
currentIndex = parentIndex;
continue;
}
}
break;
}
}
public T delete() {
if (heapList.size() == 0) {
return null;
}
if (heapList.size() == 1) {
T item = heapList.get(0);
heapList.remove(0);
return item;
}
return siftDown();
}
public T siftDown() {
T item = heapList.get(0);
T lastItem = heapList.get(heapList.size() - 1);
heapList.remove(heapList.size() - 1);
heapList.set(0, lastItem);
heapSize = heapList.size();
int currentIndex = 0;
while (currentIndex < heapSize) {
int leftIndex = (2 * currentIndex) + 1;
int rightIndex = (2 * currentIndex) + 2;
T leftItem = null;
T rightItem = null;
int currentLargestItemIndex = -1;
if (leftIndex <= heapSize - 1) {
leftItem = heapList.get(leftIndex);
}
if (rightIndex <= heapSize - 1) {
rightItem = heapList.get(rightIndex);
}
T currentLargestItem = null;
if (leftItem != null && rightItem != null) {
if (leftItem.compareTo(rightItem) >= 0) {
currentLargestItem = leftItem;
currentLargestItemIndex = leftIndex;
} else {
currentLargestItem = rightItem;
currentLargestItemIndex = rightIndex;
}
} else if (leftItem != null && rightItem == null) {
currentLargestItem = leftItem;
currentLargestItemIndex = leftIndex;
}
if (currentLargestItem != null) {
if (lastItem.compareTo(currentLargestItem) >= 0) {
break;
} else {
heapList.set(currentLargestItemIndex, lastItem);
heapList.set(currentIndex, currentLargestItem);
currentIndex = currentLargestItemIndex;
continue;
}
}
}
return item;
}
public static void main(String[] args) {
HeapPractise<Integer> heap = new HeapPractise<>();
for (int i = 0; i < 32; i++) {
heap.insert(i);
}
System.out.println(heap.getHeapList());
List<Node<Integer>> nodeArray = new ArrayList<>(heap.getHeapList()
.size());
for (int i = 0; i < heap.getHeapList().size(); i++) {
Integer heapElement = heap.getHeapList().get(i);
Node<Integer> node = new Node<Integer>(heapElement);
nodeArray.add(node);
}
for (int i = 0; i < nodeArray.size(); i++) {
int leftNodeIndex = (2 * i) + 1;
int rightNodeIndex = (2 * i) + 2;
Node<Integer> node = nodeArray.get(i);
if (leftNodeIndex <= heap.getHeapList().size() - 1) {
Node<Integer> leftNode = nodeArray.get(leftNodeIndex);
node.left = leftNode;
}
if (rightNodeIndex <= heap.getHeapList().size() - 1) {
Node<Integer> rightNode = nodeArray.get(rightNodeIndex);
node.right = rightNode;
}
}
BTreePrinter.printNode(nodeArray.get(0));
}
}
public class Node<T extends Comparable<?>> {
Node<T> left, right;
T data;
public Node(T data) {
this.data = data;
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class BTreePrinter {
public static <T extends Comparable<?>> void printNode(Node<T> root) {
int maxLevel = BTreePrinter.maxLevel(root);
printNodeInternal(Collections.singletonList(root), 1, maxLevel);
}
private static <T extends Comparable<?>> void printNodeInternal(
List<Node<T>> nodes, int level, int maxLevel) {
if (nodes.isEmpty() || BTreePrinter.isAllElementsNull(nodes))
return;
int floor = maxLevel - level;
int endgeLines = (int) Math.pow(2, (Math.max(floor - 1, 0)));
int firstSpaces = (int) Math.pow(2, (floor)) - 1;
int betweenSpaces = (int) Math.pow(2, (floor + 1)) - 1;
BTreePrinter.printWhitespaces(firstSpaces);
List<Node<T>> newNodes = new ArrayList<Node<T>>();
for (Node<T> node : nodes) {
if (node != null) {
String nodeData = String.valueOf(node.data);
if (nodeData != null) {
if (nodeData.length() == 1) {
nodeData = "0" + nodeData;
}
}
System.out.print(nodeData);
newNodes.add(node.left);
newNodes.add(node.right);
} else {
newNodes.add(null);
newNodes.add(null);
System.out.print(" ");
}
BTreePrinter.printWhitespaces(betweenSpaces);
}
System.out.println("");
for (int i = 1; i <= endgeLines; i++) {
for (int j = 0; j < nodes.size(); j++) {
BTreePrinter.printWhitespaces(firstSpaces - i);
if (nodes.get(j) == null) {
BTreePrinter.printWhitespaces(endgeLines + endgeLines + i
+ 1);
continue;
}
if (nodes.get(j).left != null)
System.out.print("//");
else
BTreePrinter.printWhitespaces(1);
BTreePrinter.printWhitespaces(i + i - 1);
if (nodes.get(j).right != null)
System.out.print("\\\\");
else
BTreePrinter.printWhitespaces(1);
BTreePrinter.printWhitespaces(endgeLines + endgeLines - i);
}
System.out.println("");
}
printNodeInternal(newNodes, level + 1, maxLevel);
}
private static void printWhitespaces(int count) {
for (int i = 0; i < 2 * count; i++)
System.out.print(" ");
}
private static <T extends Comparable<?>> int maxLevel(Node<T> node) {
if (node == null)
return 0;
return Math.max(BTreePrinter.maxLevel(node.left),
BTreePrinter.maxLevel(node.right)) + 1;
}
private static <T> boolean isAllElementsNull(List<T> list) {
for (Object object : list) {
if (object != null)
return false;
}
return true;
}
}
Please note that BTreePrinter is a code I took somewhere in Stackoverflow long back and I modified to use with 2 digit numbers.It will be broken if we move to 3 digit numbers and it is only for simple understanding of how the Heap structure looks.A fix for 3 digit numbers is to keep everything as multiple of 3.
Also due credits to Sesh Venugopal for wonderful tutorial on Youtube on Heap data structure
public class PriorityQ<K extends Comparable<K>> {
private class TreeNode<T extends Comparable<T>> {
T val;
TreeNode<T> left, right, parent;
public String toString() {
return this.val.toString();
}
TreeNode(T v) {
this.val = v;
left = null;
right = null;
}
public TreeNode<T> insert(T val, int position) {
TreeNode<T> parent = findNode(position/2);
TreeNode<T> node = new TreeNode<T>(val);
if(position % 2 == 0) {
parent.left = node;
} else {
parent.right = node;
}
node.parent = parent;
heapify(node);
return node;
}
private void heapify(TreeNode<T> node) {
while(node.parent != null && (node.parent.val.compareTo(node.val) < 0)) {
T temp = node.val;
node.val = node.parent.val;
node.parent.val = temp;
node = node.parent;
}
}
private TreeNode<T> findNode(int pos) {
TreeNode<T> node = this;
int reversed = 1;
while(pos > 0) {
reversed <<= 1;
reversed |= (pos&1);
pos >>= 1;
}
reversed >>= 1;
while(reversed > 1) {
if((reversed & 1) == 0) {
node = node.left;
} else {
node = node.right;
}
reversed >>= 1;
}
return node;
}
public TreeNode<T> remove(int pos) {
if(pos <= 1) {
return null;
}
TreeNode<T> last = findNode(pos);
if(last.parent.right == last) {
last.parent.right = null;
} else {
last.parent.left = null;
}
this.val = last.val;
bubbleDown();
return null;
}
public void bubbleDown() {
TreeNode<T> node = this;
do {
TreeNode<T> left = node.left;
TreeNode<T> right = node.right;
if(left != null && right != null) {
T max = left.val.compareTo(right.val) > 0 ? left.val : right.val;
if(max.compareTo(node.val) > 0) {
if(left.val.equals(max)) {
left.val = node.val;
node.val = max;
node = left;
} else {
right.val = node.val;
node.val = max;
node = right;
}
} else {
break;
}
} else if(left != null) {
T max = left.val;
if(left.val.compareTo(node.val) > 0) {
left.val = node.val;
node.val = max;
node = left;
} else {
break;
}
} else {
break;
}
} while(true);
}
}
private TreeNode<K> root;
private int position;
PriorityQ(){
this.position = 1;
}
public void insert(K val) {
if(val == null) {
return;
}
if(root == null) {
this.position = 1;
root = new TreeNode<K>(val);
this.position++;
return ;
}
root.insert(val, position);
position++;
}
public K remove() {
if(root == null) {
return null;
}
K val = root.val;
root.remove(this.position-1);
this.position--;
if(position == 1) {
root = null;
}
return val;
}
public static void main(String[] args) {
PriorityQ<Integer> q = new PriorityQ<>();
System.out.println(q.remove());
q.insert(1);
q.insert(11);
q.insert(111);
q.insert(1111);
q.remove();
q.remove();
q.remove();
q.remove();
q.insert(2);
q.insert(4);
}
}