Doubly Linked List - RemoveFirst Method - java

I need help with following Code:
public boolean remove(Integer value) {
if (isEmpty()) {
throw new NoSuchElementException();
}
if (!isEmpty()) {
if (head == tail) {
head = tail = null;
}
} else {
}
size--;
return false;
}
And this is my task:
"removes the first occurrence of the specified value from this list"
It s a method of a Doubly Linked List.
So far I think I did correct but I am still missing the "else" part and I have no clue what to put inside...
I also have a class with a constructor and getter- and setter- methods.
Here is my node class:
public class ListElement {
private Integer value;
private ListElement next;
private ListElement prev;
public ListElement(ListElement prev, Integer value, ListElement next) {
this.value = value;
this.next = next;
this.prev = prev;
}
public Integer getValue() {
return value;
}
public ListElement getNext() {
return next;
}
public ListElement getPrev() {
return prev;
}
public void setValue(Integer value) {
this.value = value;
}
public void setNext(ListElement next) {
this.next = next;
}
public void setPrev(ListElement prev) {
this.prev = prev;
}
}

I am assuming by the function signature that you want to delete the element with the specific value. You need to find that node and remove it:
public boolean remove(Integer value) {
if (isEmpty()) {
throw new NoSuchElementException();
}
ListElement found = head;
// Try to find it
while (null != found && !found.value.equals(value)) {
found = found.next;
}
// Not found?
if (null == found) {
throw new NoSuchElementException();
}
// Found. Unlink
if (found.prev != null) found.prev.next = found.next;
else head = found.next;
if (found.next != null) found.next.prev = found.prev;
else tail = found.prev;
size--;
return true;
}

Firstly, this if should be removed as you already test for empty
if (!isEmpty()) {
if (head == tail) {
head = tail = null;
}
} else {
}
Then you can process like:
public boolean remove(Integer value) {
if (isEmpty()) {
throw new NoSuchElementException();
}
if (head == tail) {
if (head.getValue() == value) {
head = tail = null;
} else {
// Not found, return false
size--;
return false;
}
}
ListElement current = head;
while (current != null) {
if (current.getValue() == value) {
// Found
if (current.getPrev() == null) {
// current node is head node
head = current.getNext();
current.setPrev(null);
} else if (current.next() == null) {
// current node is tail node
tail = current;
current.setNext(null);
} else {
// Current node is in the middle
ListElement prev = current.getPrev();
ListElement next = current.getNext();
prev.setNext(next);
next.setPrev(prev);
}
size--;
return true;
}
}
// Not found
size--;
return false;
}

Related

(JAVA) How do I Remove the First Element in a Circular Doubly Linked List?

I've managed to make the doubly linked list into a circular one, I'm just having trouble making a method to remove the first element. I've tried looking at examples for single linked lists but I can't seem to modify it to fit my code. Any help would be greatly appreciated.
Linkedlist Class
package LinkedListS;
public class LinkedList {
private Node first;
private Node end;
LinkedList()
{
first = end = null;
}
public void addAtStart(int x){
Node temp = new Node(x);
if(first == null)
{
first = end = temp;
}
else
{
end.setNext(temp);
temp.setNext(first);
first = temp;
}
}
public void printFromStart()
{
Node temp = first;
do {
System.out.println(temp.getData());
temp = temp.getNext();
end.setNext(null);
} while (temp != null);
}
public void searchFromStart(int elementToBeSearched)
{
Node temp = first;
while(temp != null)
{
if (temp.getData() == elementToBeSearched)
{
System.out.println("Found " + elementToBeSearched);
return;
}
temp = temp.getNext();
}
System.out.println("Didn't find " + elementToBeSearched);
}
public void removeFirstElement(){
}
Driver Class:
enter code here
public class LinkedListMain {
public static void main(String[] args) {
LinkedList ll = new LinkedList();
System.out.println("Going to add elements At Start");
ll.addAtStart(5);
ll.addAtStart(7);
ll.addAtStart(9);
ll.addAtStart(10);
System.out.println("Print the doubly linked list elements");
ll.printFromStart();
System.out.println("Search the following elements");
ll.searchFromStart(7);
ll.searchFromStart(1289);
ll.removeFirstElement();
ll.printFromStart();
}
}
Node Class:
package LinkedListS;
public class Node {
private int data;
private Node next;
private Node prev;
// Constructor to intialize/fill data
public Node(int data)
{
this.data = data;
}
// set the address of next node
public void setNext(Node temp)
{
this.next = temp;
}
// get the address of next node
public Node getNext()
{
return this.next;
}
public Node getPrev()
{
return this.prev;
}
public void setPrev(Node temp)
{
this.prev = temp;
}
// to get data of current node
public int getData()
{
return this.data;
}
}
For the removeFirstElement method I've tried these solutions with no avail:
Attempt #1
Node temp = first;
temp = null;
Attempt #2
Node temp = first;
if(first != null){
if(temp.getNext() == first){
first = null;
}
} else {
first = end;
end = first.getNext();
}
Attempt #3
Node temp = first;
if (first == null) {
System.out.println("There is no first element to remove");
} else
temp = first;
System.out.println(temp);
Attempt #4
Node temp = first;
end = null;
if(first != null){
if(temp.getNext() == temp){
first = null;
}
} else {
end = first;
first = first.getNext();
}
After scanning a few other methods that is what I found that works:
public void removeFirstElement(){
if (first != null){
first = first.getNext();
} else {
System.out.println("There is nothing to be removed");
}
}

Removing and returning item at index Linked List

package linkedList.list;
import linkedList.node.ListNode;
public interface LinkedList<N extends ListNode<T>,T>
{
public boolean isEmpty();
public int size();
public String toString();
public T[] toArray(Class<? extends T> cl);
public LinkedList<N,T> fromArray(T[] array) throws ListAccessError;
}
package linkedList.list;
import linkedList.node.ListNode;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
public abstract class BasicList<N extends ListNode<T>,T> implements LinkedList<N,T> {
N root;
int size;
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
public N getRoot() {
return root;
}
public void setRoot(N newRoot) {
root = newRoot;
}
public T[] toArray(Class<? extends T> cl) {
T[] array = (T[]) Array.newInstance(cl,size());
ListNode<T> node = getRoot();
for (int index = 0; index < size(); index++) {
array[index] = node.getValue();
node = node.getNext();
}
return array;
}
public String toString() {
if (isEmpty()) {
return "[]";
} else {
ListNode<T> currentNode = getRoot();
StringBuilder string = new StringBuilder("[" + currentNode.getValue());
while ((currentNode = currentNode.getNext()) != null) {
string.append("," + currentNode.getValue());
}
string.append("]");
return string.toString();
}
}
public String toString(int n) {
if (isEmpty()) {
return "[]";
} else {
ListNode<T> currentNode = getRoot();
StringBuilder string = new StringBuilder("[" + currentNode.getValue());
int added = 0;
while (added < n && (currentNode = currentNode.getNext()) != null) {
string.append("," + currentNode.getValue());
added++;
}
if (currentNode != null) {
string.append(",...");
}
string.append("]");
return string.toString();
}
}
}
package linkedList.list;
import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader;
import jdk.nashorn.internal.ir.IfNode;
import linkedList.node.ListNode;
import linkedList.node.SingleLinkNode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class SingleLinkList<T> extends BasicList<SingleLinkNode<T>,T> implements List<T> {
public SingleLinkList<T> fromArray(T[] array) throws ListAccessError {
for (int index = array.length-1; index >= 0; index--) {
add(0,array[index]);
}
return this;
}
ListNode<T> getNode(int index) throws ListAccessError {
// Is the list empty? If so, cannot access the node.
if (isEmpty()) {
throw new ListAccessError("Cannot get node. List is empty.");
}
// Is the given index negative? If so, this is an error.
if (index < 0) {
throw new ListAccessError("Cannot get node. Negative index.");
}
ListNode<T> currentNode = getRoot(); // start at the root
while (index != 0 && currentNode != null) { // walk along the list (if haven't reached the end by hitting null node)
currentNode = currentNode.getNext(); // by gettting next node in the list
index--; // and reducing index by one
}
// Reached the end of the list (by hitting null node)? If so, cannot access the required node.
if (currentNode == null) {
throw new ListAccessError("Cannot get node. Not enough nodes in the list.");
}
// Successfully found node by walking through until index was zero.
return currentNode;
}
public T get(int index) throws ListAccessError {
return getNode(index).getValue();
}
#Override
public void add(int index, T value) throws ListAccessError {
if (index > size() || index < 0) {
throw new ListAccessError("Index bigger than size.");
}
SingleLinkNode<T> newNode = new SingleLinkNode<T>(value);
SingleLinkNode<T> current = getRoot();
if(index==0) {
setRoot(newNode);
newNode.setNext(current);
size++;
} else {
while(--index > 0) {
current = current.getNext();
}
newNode.setNext(current.getNext());
current.setNext(newNode);
size++;
}
}
#Override
public T remove(int index) throws ListAccessError {
if (index >= size() || index < 0) {
throw new ListAccessError("Index out of bounds");
}
if (isEmpty()) {
throw new ListAccessError("List is empty cannot remove from list");
}
SingleLinkNode<T> current = getRoot();
SingleLinkNode<T> nextItem = getRoot().getNext();
return null;
}
}
package linkedList.node;
public class SingleLinkNode<T> implements ListNode<T>
{
private T value;
private SingleLinkNode<T> next;
public SingleLinkNode(T value) {
this.value = value;
next = null;
}
public SingleLinkNode(T value, SingleLinkNode<T> next) {
this.value = value;
this.next = next;
}
public T getValue() {
return value;
}
#Override
public void setValue(T value) {
this.value = value;
}
public SingleLinkNode<T> getNext() {
return next;
}
#Override
public void setNext(ListNode<T> node) {
next = (SingleLinkNode<T>) node;
}
public String toString() {
return value + (getNext() != null ? "=>" + getNext() : "");
}
}
I have just implemented the add method which takes the index and the value and inserts it into that position in the List. However when researching how to remove at the index I am unable to find anything that removes the node with just the given index. Any help is welcome and thanks in advance for any solutions!
When removing a node from a linked list at I position all you need to do is
Get to the node at i-1, let's name it 'n1'
Get the node n2=n1.next.next
Make n1.next =n2
You simply remove the "link" to the requested node at i and it's no longer part of the linked list.
Firstly, you have to check if this it is 0-th index you have to remove, so you have to shift root. Then for removing node at i-th root, all you have to do this:
nodeBeforeI.setNext(nodeBeforeI.getNext().getNext());
The complete code:
public T remove(int index) throws ListAccessError {
if (index >= size() || index < 0) {
throw new ListAccessError("Index out of bounds");
}
if (isEmpty()) {
throw new ListAccessError("List is empty cannot remove from list");
}
SingleLinkNode<T> current = getRoot();
SingleLinkNode<T> removed;
if (index == 0){
removed = current;
setRoot(current.getNext()); // setting root to root.next
}else{
for (int i = 0; i < index -1; i++){
current = current.getNext();
}
removed = current.getNext();
current.setNext(current.getNext().getNext());
}
return removed.getValue();
}

Rotating a Linked List Clockwise

I want to rotate my linked list clockwise by a certain amount.
private class Node {
private T data; // Entry in bag
private Node next; // link to next node
private Node(T dataPortion) {
this(dataPortion, null);
} // end constructor
private Node(T dataPortion, Node nextNode) {
data = dataPortion;
next = nextNode;
} // end constructor
} // end Node
public void leftShift(int num){
if (num == 0) return;
Node current = firstNode;
int count = 1;
while (count < num && current != null)
{
current = current.next;
count++;
}
if (current == null)
return;
Node kthNode = current;
while (current.next != null)
current = current.next;
current.next = firstNode;
firstNode = kthNode.next;
kthNode.next = null;
}
I managed to get my counter clockwise rotation to work but I'm kinda confused about how to get the clockwise rotation since I can't find previous nodes.
The example you asked:
private class Node {
private T data; // Entry in bag
private Node next; // link to next node
public Node(T dataPortion) {
this(dataPortion, null);
} // end constructor
public Node(T dataPortion, Node nextNode) {
data = dataPortion;
next = nextNode;
} // end constructor
T getObject() {
return data;
}
Node<T> getNext() {
return next;
}
} // end Node
public class Queue<T>{
 
private Node head;
private Node tail;
private String name;
public Queue(){
this("queue");
}
 
public Queue(String listName) {
name = listName;
head = tail = null;
}
public boolean isEmpty() {
return tail == null;
}
public void put(T item) {
Node node = new Node(item);
if (isEmpty()) // head and tail refer to same object
head = tail = node;
else { // head refers to new node
Node oldtail= tail;
tail=node;
oldtail.nextNode=tail;
}
}
public Object get() throws NoSuchElementException {
if (isEmpty()) // throw exception if List is empty
throw new NoSuchElementException();
 
T removedItem = head.data; // retrieve data being removed
 
// update references head and tail
if (head == tail)
head = tail = null;
else // locate new last node
{
head=head.nextNode;
} // end else
 
return removedItem; // return removed node data
}
public int size() {
int count = 0;
if(isEmpty()) return count;
else{
Node<T> current = head;
// loop while current node does not refer to tail
while (current != null){
count++;
if(current.nextNode==null)break;
current=current.nextNode;
}
return count;
}
public void shift(){
if(size()<=1)return;
T removed = get();
put(removed);
}
}
ListNode* Solution::rotateRight(ListNode* A, int B) {
if(A==NULL) return NULL;
ListNode *cur=A;
int len=1;
while(cur->next!=NULL){
cur=cur->next;
len++;
}
cur->next=A;
int preLen=len-B%len-1;
ListNode *pre=A;
while(preLen--)
pre=pre->next;
A=pre->next;
pre->next=NULL;
return A;
}

Difficulties with Binary Search Tree with Generics Implementation

I'm having an issue with implementing this BinarySearchTree listed below. For some context, I'm creating a binary search tree based off of an interface that requires generics and a comparable key.I think that there is a logic error in the code that is stumping me and it's in the insert method in the BinarySearchTree, but I'm not 100% sure.
Below is the class for my Node, which is used in my BST.
public class MyNodeClass<Key extends Comparable<Key>, Value>{
private Key key;
private Value value;
private MyNodeClass<Key,Value> left = null;
private MyNodeClass<Key,Value> right = null;
public MyNodeClass(Key key, Value val)
{
this.key = key;
this.value = val;
}
public void setKey(Key key){
this.key = key;
}
public void setValue(Value value){
this.value = value;
}
public Key getKey(){
return this.key;
}
public Value getValue(){
return this.value;
}
public void setLeft(MyNodeClass<Key, Value> l){
this.left = l;
}
public void setRight(MyNodeClass<Key, Value> r){
this.right = r;
}
public MyNodeClass<Key,Value> getLeft(){return this.left;}
public MyNodeClass<Key,Value> getRight(){return this.right;}
public int compareTo(Key that){
return(this.getKey().compareTo(that));
}
}
public class MyBinarySearchTree<Key extends Comparable<Key>, Value> implements BinarySearchTree<Key,Value> {
private MyNodeClass<Key, Value> root;
public MyBinarySearchTree(){
root = null;
}
#Override
public boolean isEmpty() {
return root == null;
}
#Override
public Value insert(Key key, Value val) {
MyNodeClass<Key,Value> newNode = new MyNodeClass<Key,Value>(key,val);
newNode.setKey(key);
newNode.setValue(val);
if(root==null){
root = newNode;
return(newNode.getValue());
}
else{
MyNodeClass<Key,Value> current = newNode;
MyNodeClass<Key,Value> parent;
while(true){
{
parent = current;
if(current.compareTo(key) == 1)
{
current = current.getLeft();
if(current == null)
{
parent.setLeft(newNode);
return parent.getLeft().getValue();
}
}
else if(current.compareTo(key) == -1){
current = current.getRight();
if(current == null)
{
parent.setRight(newNode);
return parent.getRight().getValue();
}
}
else{
if(current.compareTo(key) == 0){
current.setKey(key);
current.setValue(val);
return current.getValue();
}
}
}
}
}
}
#Override
public Value find(Key key) {
MyNodeClass<Key, Value> current = root;
while (current.compareTo(key) != 0)
{
if (current.compareTo(key) == 1)
{
current = current.getLeft();
} else {
current = current.getRight();
}
if(current == null)
return null;
}
return current.getValue();
}
#Override
public Value delete(Key key) {
MyNodeClass<Key,Value> current = root;
MyNodeClass<Key,Value> parent = root;
boolean isLeftChild = true;
while(current.compareTo(key) != 0) {
parent = current;
if (current.compareTo(key) == 1) {
isLeftChild = true;
current = current.getLeft();
} else {
isLeftChild = false;
current = current.getRight();
}
if(current == null)
return null;
}
if(current.getLeft() == null && current.getRight() == null) {
if (current == root) {
root = null;
} else if (isLeftChild) {
parent.setLeft(null);
} else{
parent.setRight(null);
}
return current.getValue();
}
else if(current.getRight() == null)
{
if(current == root) {
root = current.getLeft();
}
else if(isLeftChild) {
parent.setLeft(current.getLeft());
}
else{
parent.setRight(current.getLeft());
}
return current.getValue();
}
else if(current.getLeft() == null)
{
if(current == root)
root = current.getRight();
else if(isLeftChild)
parent.setLeft(current.getRight());
else
parent.setRight(current.getRight());
return current.getValue();
}
else
{
MyNodeClass<Key,Value> successor = getSuccessor(current);
if(current == root)
root = successor;
else if(isLeftChild)
parent.setLeft(successor);
else
parent.setRight(successor);
successor.setLeft(current.getLeft());
return current.getValue();
}
}
#Override
public String stringLevelOrder() {
return(LevelOrder(root));
}
private MyNodeClass<Key,Value> getSuccessor(MyNodeClass<Key,Value> deleteNode)
{
MyNodeClass<Key,Value> successorParent = deleteNode;
MyNodeClass<Key,Value> successor = deleteNode;
MyNodeClass<Key,Value> current = deleteNode.getRight();
while(current != null)
{
successorParent = successor;
successor = current;
current = current.getLeft();
}
if(successor != deleteNode.getRight())
{
successorParent.setLeft(successor.getRight());
successor.setRight(deleteNode.getRight());
}
return successor;
}
public static void main(String[] args)
{
MyBinarySearchTree<Double, MyStudent> BST = new MyBinarySearchTree<Double, MyStudent>();
MyStudent myStud1 = new MyStudent();
MyStudent myStud2 = new MyStudent();
MyStudent myStud3 = new MyStudent();
MyStudent myStud4 = new MyStudent();
MyStudent myStud5 = new MyStudent();
myStud1.init("Clarise", 1.1);
myStud2.init("Christopher", 1.2);
myStud3.init("John", 1.3);
myStud4.init("Chloe", 1.4);
myStud5.init("Goo", 1.5);
System.out.println(BST.insert(myStud1.getGPA(), myStud1));
System.out.println(BST.insert(myStud2.getGPA(), myStud2));
System.out.println(BST.insert(myStud3.getGPA(), myStud3));
System.out.println(BST.insert(myStud4.getGPA(), myStud4));
System.out.println(BST.insert(myStud5.getGPA(), myStud5));
System.out.println("Delete Key 1.0: " +BST.delete(1.3));
System.out.println("Delete Key 1.4: " +BST.delete(1.4));
System.out.println("Is Empty?: " +BST.isEmpty());
System.out.print("Find 3.9: "+ BST.find(3.9));
}
}
The result of the main is the following:
{Clarise:1.1}
{Christopher:1.2}
{John:1.3}
{Chloe:1.4}
{Goo:1.5}
Delete Key 1.0: null
Delete Key 1.4 null
Is Empty?: false
Find 3.9: null
I'm not entirely sure what the issue is and I've had some help from others, however they can't find the problem. Hoping that someone else can see something that we don't see.
In your insert method, after you've checked that root is not null, you are inserting newNode into the newNode instead of inserting it into the root.
This:
MyNodeClass<Key,Value> current = newNode;
MyNodeClass<Key,Value> parent;
Should be:
MyNodeClass<Key,Value> current = root;
MyNodeClass<Key,Value> parent;
P.S. any kind of testing would show you the problem with your insert within a minute. You could write a size() method and see that your inserts are not working, you could write a toString() method and see the state of the tree, finally you could debug.
MyNodeClass<Key,Value> current = newNode;
There is problem here.
If a tree is not empty, then your "current" should begin at root node. What you done is insert "newNode" to "newNode".
Change the code to be:
MyNodeClass<Key,Value> current = root;

Problems with Binary Tree node removal Java

I wanted to try and implement my own BST as an exercise, but I am stuck on the node removal. I cannot figure out why it doesn't work in some cases. I took the algorithm from a book, but when I test it with random elements, there are cases in which it does not remove the element, or even messes up their order so they are no longer sorted. What am I doing wrong and what would be a better way to accomplish this?
NOTE: All of the println() statements in the methods are there only for debugging purposes
class TreeNode<T extends Comparable<T>> {
T data;
TreeNode<T> left;
TreeNode<T> right;
TreeNode<T> parent;
TreeNode(T data) {
this.data = data;
}
boolean hasBothChildren() {
return hasLeftChild() && hasRightChild();
}
boolean hasChildren() {
return hasLeftChild() || hasRightChild();
}
boolean hasLeftChild() {
return left != null;
}
boolean hasRightChild() {
return right != null;
}
boolean isLeftChild() {
return this.parent.left == this;
}
boolean isRightChild() {
return this.parent.right == this;
}
}
public class BinaryTreeSet<T extends Comparable<T>> {
private TreeNode<T> root;
private void makeRoot(T element) {
TreeNode<T> node = new TreeNode<T>(element);
root = node;
}
private TreeNode<T> find(T element) {
TreeNode<T> marker = root;
TreeNode<T> found = null;
while (found == null && marker != null) {
int comparator = (marker.data.compareTo(element));
if (comparator > 0)
marker = marker.left;
else if (comparator < 0)
marker = marker.right;
else
found = marker;
}
return found;
}
private TreeNode<T> max(TreeNode<T> root) {
TreeNode<T> currentMax = root;
while (currentMax.hasRightChild()) {
currentMax = currentMax.right;
}
return currentMax;
}
// returns the inorder predecessor of node
private TreeNode<T> predecessor(TreeNode<T> node) {
return max(node.left);
}
// removes a given node with 0 or 1 children
private void removeNode(TreeNode<T> node) {
if (!node.hasChildren()) {
System.out.println("node with no children");
if (node.isLeftChild())
node.parent.left = null;
else
node.parent.right = null;
}
else {
System.out.println("node with 1 child");
if (node.isRightChild()) {
if (node.hasLeftChild())
node.parent.right = node.left;
else if (node.hasRightChild())
node.parent.right = node.right;
}
else if (node.isLeftChild()) {
if (node.hasLeftChild())
node.parent.left = node.left;
else if (node.hasRightChild())
node.parent.left = node.right;
}
}
node = null;
}
public BinaryTreeSet() {
root = null;
}
public void addElement(T element) {
if (root == null)
makeRoot(element);
else {
TreeNode<T> marker = root;
TreeNode<T> node = new TreeNode<T>(element);
boolean done = false;
while(!done) {
int comparator = marker.data.compareTo(element);
if (comparator > 0) {
if (marker.hasLeftChild())
marker = marker.left;
else {
marker.left = node;
done = true;
}
}
else if (comparator < 0) {
if (marker.hasRightChild())
marker = marker.right;
else {
marker.right = node;
done = true;
}
}
else
return;
node.parent = marker;
}
}
}
public boolean contains(T element) {
boolean found = (find(element) == null)? false : true;
return found;
}
public boolean removeElement(T element) {
TreeNode<T> node = find(element);
if (node == null)
return false;
// removal of a node with no children
if (!node.hasChildren()) {
if (node.isLeftChild()) {
node.parent.left = null;
}
else if (node.isRightChild()) {
node.parent.right = null;
}
}
// removal of a node with both children
else if (node.hasBothChildren()) {
TreeNode<T> pred = predecessor(node);
T temp = pred.data;
pred.data = node.data;
node.data = temp;
removeNode(pred);
}
// removal of a node with only 1 child
else {
if (node.isRightChild()) {
if (node.hasLeftChild())
node.parent.right = node.left;
else if (node.hasRightChild())
node.parent.right = node.right;
}
else if (node.isLeftChild()) {
if (node.hasLeftChild())
node.parent.left = node.left;
else if (node.hasRightChild())
node.parent.left = node.right;
}
}
node = null;
System.out.println("item removed: " + !contains(element));
return true;
}
}
please add following Method into BinaryTreeSet Class and call it,
which will show you current element list with Left/Right prefix.
boolean rootOncePrint = true;
public void printAllTree(TreeNode<T> startNode){
if(startNode == null) return;
//System.out.println(startNode.data);
if(rootOncePrint){
System.out.println("Root : " + startNode.data);
rootOncePrint = false;
}
if(startNode.hasChildren()){
if(startNode.hasLeftChild()){
printAllTree(startNode.left);
}
if(startNode.hasRightChild()){
printAllTree(startNode.right);
}
}
if(startNode != root){
T parentValue = startNode.parent.data;
T dataValue = startNode.data;
System.out.println(startNode.data + ((parentValue.compareTo(dataValue) > 0)?"L":"R"));
}
}
After Add this code, try to add/remove element into BinaryTreeSet so
you will get to know what's going on.
Found the bug that was causing me headaches. The problem was in the cases where I remove nodes with 0 or 1 child. I was not updating their parent nodes, so that messed up with the code. So, instead of, for example
if (node.hasLeftChild())
node.parent.right = node.left;
I should have written
if (node.hasLeftChild()) {
node.parent.left = node.left;
node.left.parent = node.parent;
}
in all cases where I deal with a single child. Also, I forgot to update the root, when the root is the target of the removeElement() function.
However, as it currently stands, I feel I have a lot of repetition in the code. I am yet to come up with a more elegant solution.
EDIT: There are other minor bugs as well, mainly in the isRightChild() and isLeftChild() functions, resulting in NullPointerException if the node in question does not have a parent.

Categories