What changes when implementing lazy deletion into a binary search tree exactly? - java

Okay so I've been looking into this for days and everytime I think I've gotten it down I start writing code and I get to a point where I just can't figure out what exactly to do.
The tree isn't recursive, so I can follow everything really until I start trying to modify it so it uses lazy deletion instead of real deletion. (Right now it nulls out the node it deletes)
What I have managed to figure out:
I added a flag to the node class to set them as deleted
I've implemented a search method that works, it even seems to register if my nodes are deleted or not(lazily)
I know that the rest of the tree class should treat the nodes that are flagged as deleted such that they are not there.
What I don't know:
I've looked at MANY resources and some say all you need to do is set
the node's deleted flag to true. Does this mean that I don't have to
worry about the linking after their flag is set?
Is an appropriate way to do this very superficial? As in, just don't let the methods report that something is found if the flag is set to deleted even though the methods do find something?
In what method(s) should I change to use lazy deletion? Only the delete() method?
If I only change the delete method, how is this picked up by the other methods?
Does the search method look okay?
Here's the rest of the code so you can see what I'm using. I'm really frustrated because I honestly understand how to delete nodes completely way better then this stupid lazy deletion implementation. It's what they teach in the book! lol
Please help... :(
Search Method
So here's my search method:
public String search(E data){
Node<E> current = root;
String result = "";
while(current != null){
if(data.compareTo(current.e) < 0){
current = current.left;
}
else if (data.compareTo(current.e) > 0){
current = current.right;
}
else{
if (current.isDeleted == false){
return result += "Found node with matching data that is not deleted!";
}
else{
return result += "Found deleted data, not usable, continuing search\n";
}
}
}
return result += "Did not find non-deleted matching node!";
}
Tree Class
Tree Code (The real deletion method is commented out at the end so I could replace it with the lazy deletion):
package mybinarytreeexample;
public class MyBinaryTree> {
private Node<E> root = null;
public class Node<E> {
public boolean isDeleted = false;
public E e = null;
public Node<E> left = null;
public Node<E> right = null;
}
public boolean insert(E e) {
// if empty tree, insert a new node as the root node
// and assign the elementy to it
if (root == null) {
root = new Node();
root.e = e;
return true;
}
// otherwise, binary search until a null child pointer
// is found
Node<E> parent = null;
Node<E> child = root;
while (child != null) {
if (e.compareTo(child.e) < 0) {
parent = child;
child = child.left;
} else if (e.compareTo(child.e) > 0) {
parent = child;
child = child.right;
} else {
if(child.isDeleted){
child.isDeleted = false;
return true;
}
return false;
}
}
// if e < parent.e create a new node, link it to
// the binary tree and assign the element to it
if (e.compareTo(parent.e) < 0) {
parent.left = new Node();
parent.left.e = e;
} else {
parent.right = new Node();
parent.right.e = e;
}
return true;
}
public void inorder() {
System.out.print("inorder: ");
inorder(root);
System.out.println();
}
private void inorder(Node<E> current) {
if (current != null) {
inorder(current.left);
System.out.printf("%3s", current.e);
inorder(current.right);
}
}
public void preorder() {
System.out.print("preorder: ");
preorder(root);
System.out.println();
}
private void preorder(Node<E> current) {
if (current != null) {
System.out.printf("%3s", current.e);
preorder(current.left);
preorder(current.right);
}
}
public void postorder() {
System.out.print("postorder: ");
postorder(root);
System.out.println();
}
private void postorder(Node<E> current) {
if (current != null) {
postorder(current.left);
postorder(current.right);
System.out.printf("%3s", current.e);
}
}
public String search(E data){
Node<E> current = root;
String result = "";
while(current != null){
if(data.compareTo(current.e) < 0){
current = current.left;
}
else if (data.compareTo(current.e) > 0){
current = current.right;
}
else{
if (current.isDeleted == false){
return result += "Found node with matching data that is not deleted!";
}
else{
return result += "Found deleted data, not usable, continuing search\n";
}
}
}
return result += "Did not find non-deleted matching node!";
}
public boolean delete(E e) {
}
// an iterator allows elements to be modified, but can mess with
// the order if element not written with immutable key; it is better
// to use delete to remove and delete/insert to remove or replace a
// node
public java.util.Iterator<E> iterator() {
return new PreorderIterator();
}
private class PreorderIterator implements java.util.Iterator<E> {
private java.util.LinkedList<E> ll = new java.util.LinkedList();
private java.util.Iterator<E> pit= null;
// create a LinkedList object that uses a linked list of nodes that
// contain references to the elements of the nodes of the binary tree
// in preorder
public PreorderIterator() {
buildListInPreorder(root);
pit = ll.iterator();
}
private void buildListInPreorder(Node<E> current) {
if (current != null) {
ll.add(current.e);
buildListInPreorder(current.left);
buildListInPreorder(current.right);
}
}
// check to see if their is another node in the LinkedList
#Override
public boolean hasNext() {
return pit.hasNext();
}
// reference the next node in the LinkedList and return a
// reference to the element in the node of the binary tree
#Override
public E next() {
return pit.next();
}
#Override
public void remove() {
throw new UnsupportedOperationException("NO!");
}
}
}
// binary search until found or not in list
// boolean found = false;
// Node<E> parent = null;
// Node<E> child = root;
//
// while (child != null) {
// if (e.compareTo(child.e) < 0) {
// parent = child;
// child = child.left;
// } else if (e.compareTo(child.e) > 0) {
// parent = child;
// child = child.right;
// } else {
// found = true;
// break;
// }
// }
//
//
// if (found) {
// // if root only is the only node, set root to null
// if (child == root && root.left == null && root.right == null)
// root = null;
// // if leaf, remove
// else if (child.left == null && child.right == null) {
// if (parent.left == child)
// parent.left = null;
// else
// parent.right = null;
// } else
// // if the found node is not a leaf
// // and the found node only has a right child,
// // connect the parent of the found node (the one
// // to be deleted) to the right child of the
// // found node
// if (child.left == null) {
// if (parent.left == child)
// parent.left = child.right;
// else
// parent.right = child.right;
// } else {
// // if the found node has a left child,
// // the node in the left subtree with the largest element
// // (i. e. the right most node in the left subtree)
// // takes the place of the node to be deleted
// Node<E> parentLargest = child;
// Node<E> largest = child.left;
// while (largest.right != null) {
// parentLargest = largest;
// largest = largest.right;
// }
//
// // replace the lement in the found node with the element in
// // the right most node of the left subtree
// child.e = largest.e;
//
// // if the parent of the node of the largest element in the
// // left subtree is the found node, set the left pointer of the
// // found node to point to left child of its left child
// if (parentLargest == child)
// child.left = largest.left;
// else
// // otherwise, set the right child pointer of the parent of
// // largest element in the left subtreeto point to the left
// // subtree of the node of the largest element in the left
// // subtree
// parentLargest.right = largest.left;
// }
//
// } // end if found
//
// return found;

What changes is that your tree only grows in term of real space used, and never shrinks. This can be very useful if you choose a list as a data-structure to implement your tree, rather than the usual construct Node E {V value; E right; E; left}. I will come back on this later.
I've looked at MANY resources and some say all you need to do is set
the node's deleted flag to true. Does this mean that I don't have to
worry about the linking after their flag is set?
Yes, if by linking you mean node.left, node.right. Delete simply mark as deleted and that's it. It change nothing else, and it should not, because x.CompareTo(y) must be still working even if x or y are marked as deleted
Is an appropriate way to do this very superficial? As in, just don't
let the methods report that something is found if the flag is set to
deleted even though the methods do find something?
Well by definition of this method "something" means a node without the deleted flag. Anything with the deleted flag is "nothing" for the user of the tree.
what method(s) should I change to use lazy deletion? Only the delete()
method?
Of course not. You already changed the search method yourself. Let's take the isEmpty(). You should keep a counter of deleted nodes and one of total nodes. If they are equal the tree is empty. Otherwise the tree is not.
There is a small bug in your algorithm. When you insert and find out that you land on a deleted node, you just unmark that node. You must also set the value of the node. After all compareTo doesnt insure all fields are strictly equal, just that the objects are equivalent.
if(child.isDeleted){
child.isDeleted = false;
child.e = e; <---- missing
return true;
}
There might be others.
Side Note:
As said before one instance where this method is useful is a tree backed by an list (let's say array list). With this method the children of element at position i are at position 2*i+1 and 2*i+2. Usually when you delete a node p with children, you replace that node with the leftmost node q of the right subtree (or rightmost node in the left subtree). Here you can just mark p as deleted and swap the value of the deleted node and leftmost. Your array stays intact in memory

Related

Using String as BST key in java

I have a binary search tree which stores objects. Can I use String value is a key, It only stores the first key and also searches only the first value, all other keys find returns a null
The first Value is A
this my code: help!
public void addNode(String key, String name) {
// Create a new Node and initialize it
Node newNode = new Node(key, name);
// If there is no root this becomes root
if (root == null) {
root = newNode;
} else {
// Set root as the Node we will start
// with as we traverse the tree
Node focusNode = root;
// Future parent for our new Node
Node parent;
while (true) {
parent = focusNode;
if (key.compareTo(focusNode.name) <= 0) {
// Switch focus to the left child
focusNode = focusNode.leftChild;
// If the left child has no children
if (focusNode == null) {
// then place the new node on the left of it
parent.leftChild = newNode;
return; // All Done
}
} else if(key.compareTo(focusNode.name) >= 0){ // If we get here put the node on the right
focusNode = focusNode.rightChild;
// If the right child has no children
if (focusNode == null) {
// then place the new node on the right of it
parent.rightChild = newNode;
return; // All Done
}
}
}
}
}
enter image description here
From what I see, your problem is that you are comparing keys with values (name in your case). For example, instead of:
if (key.compareTo(focusNode.name) <= 0) {...
Try:
if (key.compareTo(focusNode.key) <= 0) {...
Also, another problem is that you are never handling the case that the two keys are equal, but instead you proceed to the left child. You probably want to do something else at that point, I'd guess updating the name and returning from the method.

Setting parents in tree

I have a huffman binary tree that starts with an empty node a.
A points to a left node and a right node, which also point to left and right nodes. Is it possible to set the parent nodes for each node recursively after having this tree?
This is the code I am thinking:
public Node setParents(Node n)
{
if(n.getZero() == null && n.getOne() == null)
{
return n;
}
Node a = setParents(n.getZero()); // Zero being left
a.setParent(n);
Node b = setParents(n.getOne()); // One being right.
b.setParent(n);
}
Here is how I am currently creating the tree by using a priority queue with values sorted least to greatest.
public Node createTree(PriorityQueue<Node> pq)
{
while(pq.size() > 1)
{
Node n = new Node();
Node a = pq.poll();
if(pq.size() > 0)
{
Node b = pq.poll();
n = new Node(a.getFrequency() + b.getFrequency());
n.setZero(a);
a.setWhich(0);
a.setParent(n);
n.setOne(b);
b.setWhich(1);
b.setParent(n);
}
else
{
n = new Node(a.getFrequency());
n.setZero(a);
a.setWhich(0);
n.setParent(n);
n.setOne(null);
}
pq.add(n);
}
Node n = pq.poll();
n.setParent(null);
setParents(n.getZero());
setParents(n.getOne());
return n;
}
I just need to make sure each node has a parent, which I don't know where to start from here.. Any help?
Some comments to your code that may help
1 . Do not use getters and setters in your study samples for simple assignments and reads, they are hard to understand.
2 . If you prepare some object do not mix this preparation with others
n.setZero(a);
a.setWhich(0);
a.setParent(n);
n.setOne(b);
3 . From what I understand there is a chance to get NPE
if(pq.size() > 0) {
Node b = pq.poll();
}
}
Node n = pq.poll();
n.setParent(null); <- n can be null
4 . Java has nice feature called Enums for this
a.setWhich(0);
b.setWhich(1);
Here is how to set parents starting from the root
public void fixParents(Node parentNode)
{
if (parentNode.zero != null) {
parentNode.zero.parent = parentNode;
fixParents(parentNode.zero);
}
if (parentNode.one != null) {
parentNode.one.parent = parentNode;
fixParents(parentNode.one);
}
}
UPD
One more thought. You set parents in your tree building function. So you should just check that parents are correct but not re-setting them.
public void checkParents(Node parentNode) throws Exception
{
if (parentNode.zero != null) {
if (parentNode.zero.parent != parentNode) {
throw new Exception( here include info about the parentNode.zero );
}
checkParents(parentNode.zero);
}
if (parentNode.one != null) {
if (parentNode.one.parent != parentNode) {
throw new Exception( here include info about the parentNode.one );
}
checkParents(parentNode.one);
}
}

BST Only Keeps Last Inserted Value and Makes it Root

I'm trying to populate a binary search tree using an insert(), however when every I 'print' the contents of my BST, I only get the last item that was inserted into the BST. What do I need to fix to make sure all of my value are retaining in the BST?
From debuggin, I think that my problem is that my public void insert() is setting the new value to root evertime it is called. I don't know how to fix it?
Here is my BST CLass:
public class BinarySearchTree<T extends Comparable<T>> {
private class BinarySearchTreeNode<E>{
public BinarySearchTreeNode<E> left, right;
private E data;
private BinarySearchTreeNode (E data) {
this.data = data;
}
}
private BinarySearchTreeNode<T> root;
public boolean isEmpty() {
return root == null;
}
private BinarySearchTreeNode<T> insert(T value, BinarySearchTreeNode<T> ptr) {
if (ptr == null){
ptr = new BinarySearchTreeNode<>(value);
return ptr;
}
int compare = value.compareTo(ptr.data); //when ptr != null, this line and below should execute for each bstStrings.inster(x)
/* pass the value (s1...sN) when compared to (ptr.data) to compare
* when value and ptr.data == 0 re
*/
if (compare == 0) {
return ptr;
}
if (compare < 0) {
while (ptr.left != null){
ptr = ptr.left;
if (ptr.left == null) {//found insertion point
BinarySearchTreeNode<T> node = new BinarySearchTreeNode<>(value);
ptr = ptr.left;
ptr = node;
return ptr;
}
}
}
else {
return insert(value, ptr.left);
}
if (compare > 0) {
if (ptr.right == null) {
BinarySearchTreeNode<T> node = new BinarySearchTreeNode<>(value);
ptr = ptr.right;
ptr = node;
return ptr;
}
}
else {
return insert(value, ptr.right);
}
return ptr;
}
public void insert(T value) {
root = insert(value, root); //****Where I believe the problem is******
}
private void printTree(BinarySearchTreeNode<T>node){
if(node != null){
printTree(node.left);
System.out.println(" " + node.data);
printTree(node.right);
}
}
public void printTree(){
printTree(root);
System.out.println();
}
}
For added context here is my Main() where I am calling the insert() and trying to insert strings into the BST:
public class Main {
public static void main(String[] args) {
BinarySearchTree<String> bstStrings = new BinarySearchTree<String>();
String s = "Hello";
String s1 = "World";
String s2 = "This Morning";
String s3 = "It's";
bstStrings.insert(s);
bstStrings.insert(s1);
bstStrings.insert(s2);
bstStrings.insert(s3); //the only inserted value that is printed below
bstStrings.printTree();
System.out.println();
System.out.println("You should have values above this line!");
}
}
Lastly my console output:
It's
You should have values above this line!
Some hints:
I don't see any recursive calls inside insert. How would you traverse the BST without appropriate recursive calls (into the left or right subtree of the current node based on the value)? I do see some commented out code that looks like it would perform those calls. Why are they commented out?
You're returning the newly inserted node, which you're then setting as root. This will set the root to point to the new node every time. I don't think that's what you want.
If you're trying to handle the special case where the tree is empty, all you need to do is check to see if root is null, then set the new node to that.
There really is no need to return ptr. Since your BST maintains a reference to root, you always have a reference to the root of the tree. Every time you insert, you start with the root and then recursively traverse the tree until you find a suitable place to insert the new node. If you really must return the reference, then you most certainly should not be setting root to that new node!
Here is some pseudocode to help you out:
// Recursive function that inserts a value into a BST
function insert(node, value):
//Handles the case where you have no nodes in the tree, so root is null
if node is null:
node = new Node(value)
// If the value is lesser than the current node's value, we need to insert it
// somewhere in the right subtree
else if value < node.value:
if node.right is null:
// This node doesn't have a right child, so let's insert the new node here
node.right = new Node(value)
else:
// This node has a right child, so let's go further into this subtree to
// find the right place to insert the new node
insert(node.right, value)
// If the value is greater than the current node's value, we need to insert it
// somewhere in the left subtree
else if value > node.value:
if node.left is null:
// This node doesn't have a left child, so let's insert the new node here
node.left = new Node(value)
else:
// This node has a left child, so let's go further into this subtree to
// find the right place to insert the new node
insert(node.left, value)
else:
// A node with this value already exists so let's print out an erro
error("Node with that value already exists")
end function

java Delete a Binary Tree node containing two children

This is the last case where the node to be deleted has two children. I cant figure out what I am doing wrong . Please help.
//BTNode has two children
else if (u.getLeft() != null && u.getRight() != null){
//if node to delete is root
BTNode<MyEntry<K,V>> pred = u.getRight();
while (pred.getLeft().element() != null){
pred = pred.getLeft();
}
BTNode<MyEntry<K,V>> predParent = pred.getParent();
if (!hasRightChild(pred)){
predParent.setLeft(new BTNode<MyEntry<K,V>>(null,predParent,null,null));}
if (hasRightChild(pred)){
BTNode<MyEntry<K,V>> predChild = pred.getRight();
predParent.setLeft(predChild);
predChild.setParent(predParent);
}
return returnValue;
ok so modify it like this ??
u.setElement(succ.element());
BTNode<MyEntry<K,V>> succParent = succ.getParent();
if (!hasLeftChild(succ)){
succParent.setRight(new BTNode<MyEntry<K,V>>(null,succParent,null,null));}
if (hasLeftChild(succ)){
BTNode<MyEntry<K,V>> predChild = succ.getLeft();
succParent.setRight(predChild);
predChild.setParent(succParent);
}
return returnValue;
From wikipedia:
Deleting a node with two children: Call the node to be deleted N. Do
not delete N. Instead, choose either its in-order successor node or
its in-order predecessor node, R. Replace the value of N with the
value of R, then delete R.
So, take for example the left children, and then find the rightmost leaf in that subtree, then replace the information of the node to delete with that of the leaf, and then delete that leaf easily.
You might want to create a function that returns the rightmost leaf from a subtree.
I have given the code for deletion of a node in a BST which would work for any condition and that too using a for loop.
public void delete(int key) {
Node<E> temp = find(key);
System.out.println(temp.key);
for (;;) {
// case 1 : external node
if (temp.isExternal()) {
if (temp.getParent().getrChild() == temp) {
temp.parent.rightchild = null;
temp = null;
} else {
temp = null;
}
break;
}
// case2 : one child is null
else if ((temp.getlChild() == null) || (temp.getrChild() == null)) {
if ((temp.parent.leftchild != null) && temp.getParent().getlChild().key == temp.key) {
if (temp.getlChild() == null) {
temp.getParent().setLeft(temp.getrChild());
temp.getrChild().setParent(temp.getParent());
break;
}
else
temp.getParent().setLeft(temp.getlChild());
temp.getlChild().setParent(temp.getParent());
}
else {
if (temp.rightchild != null) {
System.out.println("in");
temp.getParent().setRight(temp.getrChild());
temp.getrChild().setParent(temp.getParent());
break;
}
else
temp.getParent().setRight(temp.getlChild());
temp.getlChild().setParent(temp.getParent());
}
break;
}
// case 3 : has both the children
else {
int t = temp.key;
temp.key = temp.getlChild().key;
temp.getlChild().key = t;
temp = temp.getlChild();
continue;
}
}
}

Write a method to find the common elements between two BSTs, and insert them in 3rd BST

I got an insert method and a search method, and I was thinking of a way to loop through the binary search tree and use a method like get nodes then search for it on the other binary search tree and if it comes true then I insert it that element, but the problem is I can't come up with a way to get the nodes based on index because its different than linkedList for example and can't think of a way to get the nodes to begin with; to sum up, I actually don't the proper way to start to solve that question.
public class BinarySearchTree extends BinaryTree {
//default constructor
//Postcondition: root = null;
public BinarySearchTree() {
super();
}
//copy constructor
public BinarySearchTree(BinarySearchTree otherTree) {
super(otherTree);
}
public class BinaryTree {
//Definition of the node
protected class BinaryTreeNode {
DataElement info;
BinaryTreeNode llink;
public DataElement getInfo() {
return info;
}
public BinaryTreeNode getLlink() {
return llink;
}
public BinaryTreeNode getRlink() {
return rlink;
}
BinaryTreeNode rlink;
}
protected BinaryTreeNode root;
//default constructor
//Postcondition: root = null;
public BinaryTree() {
root = null;
}
//copy constructor
public BinaryTree(BinaryTree otherTree) {
if (otherTree.root == null) //otherTree is empty
{
root = null;
} else {
root = copy(otherTree.root);
}
}
public BinaryTreeNode getRoot() {
return root;
}
public boolean search(DataElement searchItem) {
BinaryTreeNode current;
boolean found = false;
current = root;
while (current != null && !found) {
if (current.info.equals(searchItem)) {
found = true;
} else if (current.info.compareTo(searchItem) > 0) {
current = current.llink;
} else {
current = current.rlink;
}
}
return found;
}
public int countEven() {
return countEven(root);
}
public void insert(DataElement insertItem) {
BinaryTreeNode current;
BinaryTreeNode trailCurrent = null;
BinaryTreeNode newNode;
newNode = new BinaryTreeNode();
newNode.info = insertItem.getCopy();
newNode.llink = null;
newNode.rlink = null;
if (root == null) {
root = newNode;
} else {
current = root;
while (current != null) {
trailCurrent = current;
if (current.info.equals(insertItem)) {
System.out.println("The insert item is already in" + "the list -- duplicates are" + "not allowed.");
return;
} else if (current.info.compareTo(insertItem) > 0) {
current = current.llink;
} else {
current = current.rlink;
}
}
if (trailCurrent.info.compareTo(insertItem) > 0) {
trailCurrent.llink = newNode;
} else {
trailCurrent.rlink = newNode;
}
}
}
Traverse down to the left end of one tree, compare it with the root node of the other tree. If found equal, insert it into your third tree. If unequal, then check if it's less than or greater than the root of second tree. If less than, then traverse to the left child of the second tree and call your search method again, else, traverse to the right child of the second tree and call your search method again. Then repeat the whole process with the right node of the opposing starting node of first tree that you chose and call the search method again. Keep moving up the first tree as you repeat the process.
Here's a sample code(keeping in mind you have not provided any details about your trees whatsoever):
void search(Node node1, Node root2){
if(root2 == null)
return;
if(node1.data == root2.data){
//copy to your third tree
return;
}
else{
if(node1.data < root2.data){
root2 = root2.left;
search(node1, root2);
}
else{
root2 = root2.right;
search(node1, root2);
}
}
}
void common(Node root1, Node root2){
if(root1 != null){
common(root1.left, root2);
search(root1, root2);
common(root1.right, root2);
}
}
I'm assuming you need to modify the BinarySearchTree class, so the following is written with that assumption.
You can traverse the tree by first calling getRoot() which will return the root of the tree (a BinaryTreeNode) then access the nodes' left and right children by calling getLLink() and getRLink(), respectively. From each node you can get its value via getInfo that you can search for in the other tree (by calling the search() method on the second tree).
Note: as it is, you can only call methods on the nodes from within methods of BinarySearchTree as access to BinaryTreeNode is restricted to BinaryTree and classes deriving from it (for which BinarySearchTree qualifies)

Categories