This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 4 years ago.
I'm working on a Binary Search Tree assignment, and I was testing what I thought was the finished product when I saw that when I added a number to the tree and then tried to check it's predecessor/successor (by putting it into an array using in order traverse and then checking the index before/after it) it just...didn't work. Any time I try to check the predecessor/successor of a value I just put in the middle of the tree, it wigs out with an ArrayIndexOutOfBoundsException. Important note is that simply printing out using inordertraverse (called printInOrder in the code) works perfectly.
Since printing the inorder traverse works, I can assume my tree isn't the problem. The only other thing is the array, right? Am I missing something obvious?
Here's the code!
public class BST implements BSTInterface
{
//Variables/Fields
private BNode root;
//Constructors
public BST(int data)
{
root = new BNode(data);
}
//Public Methods
public boolean add(int data)
{
if(!contains(data))
{
root = addEntry(root, data);
return true;
}
else
return false;
}
public boolean contains(int data)
{
return containsNode(root, data);
}
public boolean remove(int data)
{
if(contains(data))
{
root = deleteNode(root, data);
return true;
}
else
return false;
}
public int[] toArray()
{
int[] output = new int[root.numNodes()];
inorderTraverse(output, 0, root);
return output;
}
public void printInOrder()
{
printIn(root);
}
public void printPreOrder()
{
printPre(root);
}
public void printPostOrder()
{
printPost(root);
}
//Private methods/classes
private class BNode
{
private int data;
private BNode leftChild;
private BNode rightChild;
public BNode(int data)
{
this.data = data;
leftChild = null;
rightChild = null;
}
public int getData()
{
return data;
}
public void setData(int newData)
{
data = newData;
}
public BNode getLeftChild()
{
return leftChild;
}
public BNode getRightChild()
{
return rightChild;
}
public void setRightChild(BNode node)
{
rightChild = node;
}
public void setLeftChild(BNode node)
{
leftChild = node;
}
public int numNodes()
{
int leftNum = 0;
int rightNum = 0;
if(leftChild != null)
leftNum = leftChild.numNodes();
if(rightChild != null)
rightNum = rightChild.numNodes();
return 1+leftNum+rightNum;
}
}
private BNode addEntry(BNode current, int data)
{
if(current == null)
return new BNode(data);
if(data < current.getData())
current.setLeftChild(addEntry(current.getLeftChild(), data));
else if(data > current.getData())
current.setRightChild(addEntry(current.getRightChild(), data));
return current;
}
private boolean containsNode(BNode current, int entry)
{
if(current == null)
return false;
if(entry == current.getData())
return true;
if(entry < current.getData())
return containsNode(current.getLeftChild(), entry);
else
return containsNode(current.getRightChild(), entry);
}
private BNode deleteNode(BNode current, int data)
{
if(current == null)
return null;
if(data == current.getData())
{
if(current.getLeftChild() == null && current.getRightChild() == null) //No children
return null;
if(current.getRightChild() == null) //Only right child
return current.getLeftChild();
if(current.getLeftChild() == null) //Only left child
return current.getRightChild();
int smallestChild = findSmallest(current.getRightChild());
current.setData(smallestChild);
current.setRightChild(deleteNode(current.getRightChild(), smallestChild));
return current;
}
if(data < current.getData())
{
current.setLeftChild(deleteNode(current.getLeftChild(), data));
return current;
}
else
current.setRightChild(deleteNode(current.getRightChild(), data));
return current;
}
private int findSmallest(BNode root)
{
return root.getLeftChild() == null ? root.getData() : findSmallest(root.getLeftChild());
}
private void inorderTraverse(int[] array, int count, BNode node)
{
if(node != null)
{
inorderTraverse(array, count, node.getLeftChild());
array[count] = node.getData();
count++;
inorderTraverse(array, count, node.getRightChild());
}
}
private void printIn(BNode node)
{
if(node != null)
{
printIn(node.getLeftChild());
System.out.print(node.getData() + " ");
printIn(node.getRightChild());
}
}
private void printPre(BNode node)
{
if(node != null)
{
System.out.print(node.getData() + " ");
printPre(node.getLeftChild());
printPre(node.getRightChild());
}
}
private void printPost(BNode node)
{
if(node != null)
{
printPost(node.getLeftChild());
printPost(node.getRightChild());
System.out.print(node.getData() + " ");
}
}
}
along with the driver program:
import java.util.Scanner;
public class BSTDemoReel
{
public static void main(String[] args)
{
System.out.println("This search tree only handles integers! Thanks in advance!\n\n");
Scanner keyboard = new Scanner(System.in);
//Variables
String input;
String choice = "";
int num;
int index;
boolean found;
//Starting
System.out.println("Please enter the initial sequence of values:\n");
input = keyboard.nextLine();
String[] splitInput = input.split(" ");
int[] intInputArray = new int[splitInput.length];
for(int count = 0; count < splitInput.length; count++)
{
intInputArray[count] = Integer.parseInt(splitInput[count]);
}
BST searchTree = new BST(intInputArray[0]);
for(int count = 1; count < intInputArray.length; count++)
{
searchTree.add(intInputArray[count]);
}
System.out.print("Pre-order: ");
searchTree.printPreOrder();
System.out.println();
System.out.print("In-order: ");
searchTree.printInOrder();
System.out.println();
System.out.print("Post-order: ");
searchTree.printPostOrder();
System.out.println();
//Menu
while(!choice.equals("E"))
{
System.out.print("Command? ");
choice = keyboard.next();
choice = choice.toUpperCase();
switch(choice)
{
case "I": num = keyboard.nextInt();
if(searchTree.contains(num))
System.out.println(num + " already exists. Please try again.");
else
{
searchTree.add(num);
System.out.print("In-order: ");
searchTree.printInOrder();
System.out.println();
}
break;
case "D": num = keyboard.nextInt();
if(!searchTree.contains(num))
System.out.println(num + " does not exist. Please try again.");
else
{
searchTree.remove(num);
System.out.print("In-order: ");
searchTree.printInOrder();
System.out.println();
}
break;
case "P": num = keyboard.nextInt();
if(searchTree.contains(num))
{
int[] array = searchTree.toArray();
index = 0;
found = false;
while(!found)
{
if(num == array[index])
found = true;
else
index++;
}
if(index != 0)
System.out.println(array[index-1]);
else
System.out.println("That was the first one!");
}
else
System.out.println(num + " does not exist! Please try again!");
break;
case "S": num = keyboard.nextInt();
if(searchTree.contains(num))
{
int[] array = searchTree.toArray();
index = 0;
found = false;
while(!found)
{
if(num == array[index])
found = true;
else
index++;
}
if(index != array.length-1)
System.out.println(array[index+1]);
else
System.out.println("That was the last one!");
}
else
System.out.println(num + " does not exist! Please try again!");
break;
case "E": System.out.println("Was a tricky one! Thanks for playing ;P");
break;
case "H": System.out.println("I Insert a value\n" +
"D Delete a value\n" +
"P Find predecessor\n" +
"S Find successor\n" +
"E Exit the program\n" +
"H Display this message");
break;
default: System.out.println("Invalid command. Type H for help.");
break;
}
}
keyboard.close();
}
}
If you add a couple of lines of code to print out the array returned by searchTree.toArray() before you enter the while loop that examines the array to find the value specified with the P or S commands then you'll see the cause of the problem. The array is not filled in correctly. The desired value might not be present in the array, which means that found will never become True and the while loop will continue to increment index until it exceeds the size of the array and triggers the exception that you're seeing.
Since the array is supposed to be populated by inorderTraverse(), this suggests that that function isn't doing its job correctly. The reason why it is misbehaving is that its inner recursive calls to itself do not modify the value of the count variable for the caller. count is a simple int variable, therefore the count++ statement inside the recursive call does not affect the value of count in the calling function.
Your best options are either to change inorderTraverse() so that it returns the index of the array element that should be filled in next, or change count to be an Object that contains an int member whose updated value will be visible to the caller after it has been incremented inside the recursively called function.
Since this is an assignment I'm not going to show a corrected version of the program. The change is small, so given what you've done so far I expect that you won't have much trouble making it work.
BTW, your program is missing implementations of printIn(), printPre() and printPost(). They're not hard to write, but it's an extra hurdle for anyone who might have been interested in helping you tackle the problem. That might be at least part of the reason why no-one else has offered an answer yet. The easier you make it for people to reproduce the problem, the more likely it is that you'll get answers.
I'm trying to implement a generic binary search tree. I'm inserting 7 integers and want them to return with inOrder traversal however it's only returning 4 values out of order. Then I check if the tree contains a specific value but it always returns null and i'm unsure why. I'll post the code below, any idea's on why my output is what it is? I know my issues are probably within my insert and find methods, but unsure why, some clarification would be nice. Appreciate any advice, thanks!
Output when inserting integers 15, 10, 20, 5, 13, 11, 19:
run:
InOrder:
Inorder traversal: 10 15 11 19
Is 11 in the tree? null
BUILD SUCCESSFUL (total time: 0 seconds)
Node.class:
class Node<E> {
protected E element;
protected Node<E> left;
protected Node<E> right;
public Node(E e) {
element = e;
}
}
BinarySearchTree.class:
class BinarySearchTree<E extends Comparable<E>> {
private Node<E> root;
public BinarySearchTree() {
root = null;
}
public Node find(E e) {
Node<E> current = root;
while (e.compareTo(current.element) != 0) {
if (e.compareTo(current.element) < 0) {
current = current.left;
}
else {
current = current.right;
}
if (current == null) {
return null;
}
}
return current;
}
public void insert(E e) {
Node<E> newNode = new Node<>(e);
if (root == null) {
root = newNode;
} else {
Node<E> current = root;
Node<E> parent = null;
while (true) {
parent = current;
if (e.compareTo(current.element) < 0) {
current = current.left;
}
if (current == null) {
parent.left = newNode;
return;
} else {
current = current.right;
if (current == null) {
parent.right = newNode;
return;
}
}
}
}
}
public void traverse(int traverseType) {
switch(traverseType) {
case 1: System.out.print("\nPreorder traversal: ");
preOrder(root);
break;
case 2: System.out.print("\nInorder traversal: ");
inOrder(root);
break;
case 3: System.out.print("\nPostorder traversal: ");
postOrder(root);
break;
}
System.out.println();
}
private void inOrder(Node<E> localRoot) {
if (localRoot != null) {
inOrder(localRoot.left);
System.out.print(localRoot.element + " ");
inOrder(localRoot.right);
}
}
private void preOrder(Node<E> localRoot) {
if (localRoot != null) {
System.out.print(localRoot.element + " ");
preOrder(localRoot.left);
preOrder(localRoot.right);
}
}
private void postOrder(Node<E> localRoot) {
if (localRoot != null) {
postOrder(localRoot.left);
postOrder(localRoot.right);
System.out.print(localRoot.element + " ");
}
}
}
Main class:
public class BST_Test{
public static void main(String[] args) {
testInteger();
}
static void testInteger() {
BinarySearchTree<Integer> itree = new BinarySearchTree<>();
itree.insert(15);
itree.insert(10);
itree.insert(20);
itree.insert(5);
itree.insert(13);
itree.insert(11);
itree.insert(19);
// Traverse tree
System.out.print("InOrder: ");
itree.traverse(2);
// Search for an element
System.out.println("Is 11 in the tree? " + itree.find(11));
}
}
The cause is your poorly formatted code is hiding the fact your insert method is incorrect.
This if statement does not have an opening curly brace { (and subsequently the closing curly brace } since it compiles), so as a result only the subsequent statement is included in this if block:
if (e.compareTo(current.element) < 0)
current = current.left
This means the following is executed regardless of whether the condition above is true...
if (current == null) {
parent.left = newNode;
return;
} ...
... and as a result if current != null, your insertion will then proceed to the right:
... else {
current = current.right;
if (current == null) {
parent.right = newNode;
return;
}
}
In full your current erroneous code, when formatted/indented appropriately is:
public void insert(E e) {
Node<E> newNode = new Node<>(e);
if (root == null) {
root = newNode;
} else {
Node<E> current = root;
Node<E> parent = null;
while (true) {
parent = current;
if (e.compareTo(current.element) < 0) // missing { ...
current = current.left; // ... so only this is in the if block
if (current == null) {
parent.left = newNode;
return;
} else { // oops, this should be else to the e.compareTo(current.element) < 0 condition
current = current.right;
if (current == null) {
parent.right = newNode;
return;
}
}
}
}
}
Fixed code (assuming duplicates are allowed):
public void insert(E e) {
Node<E> newNode = new Node<>(e);
if (root == null) {
root = newNode;
} else {
Node<E> current = root;
Node<E> parent = null;
while (true) {
parent = current;
if (e.compareTo(current.element) < 0) {
current = current.left;
if (current == null) {
parent.left = newNode;
return;
}
} else {
current = current.right;
if (current == null) {
parent.right = newNode;
return;
}
}
}
}
}
Moral of the story: Keeping your code well-formatted and using curly braces for blocks will save you headaches.
I am brushing up on some simple data structures and I am having trouble making the rotations in my BST work properly.
public class BinarySearchTree {
private static class Node {
Node parent; //null for root node
Node left;
Node right;
int data;
//constructor for node
Node(int newData) {
left = null;
right = null;
parent = null;
data = newData;
}
}
private Node root; //root null in empty
//search methods
public boolean search(int data) {
return search(root,data); //true if exists
}
private boolean search(Node n, int data) {
if(n == null)
return false; //node doesn't exist
if(data == n.data) //found
return true;
else if(data < n.data) //data on left if exists
return search(n.left, data);
else //data on right if it exists
return search(n.right,data);
}
public Node findNode(int data) {
return findNode(root,data);
}
private Node findNode(Node n, int data) {
if(n == null)
return n; //nothing exists here
else if (data < n.data) //data should be on left if it exists
return findNode(n.left,data);
else if(data > n.data) //data should be on right if it exists
return findNode(n.right,data);
else
return n; //found it
}
//recursive insertion
public void insertNode(int data) {
root = insertNode(root,null,data);
}
private Node insertNode(Node n, Node parentNode, int data) {
if(n == null) {
n = new Node(data); //if node doesn't exist add it here
n.parent = parentNode;
}
else {
if(data <= n.data) {
n.left = insertNode(n.left,n,data);
} else {
n.right = insertNode(n.right,n,data);
}
}
return n; //return self at end (will go back to root)
}
//rotations
public void rotateLeft(Node n) {
Node y = n.right;
n.right = y.left; //y's left subtree into n's right subtree
if(y.left != null)
y.left.parent = n;
y.parent = n.parent;
//link n's parent to y
if(n.parent == null) //check to see if we are at root
root = y;
else if(n == n.parent.left) //n on left of parent
n.parent.left = y;
else //n on right of parent
n.parent.right = y;
y.left = n;
n.parent = y; //n on y's left
}
public void rotateRight(Node n) {
Node y = n.left;
n.left = y.right;
if(y.right != null)
y.right.parent = n;
y.parent = n.parent;
if(n.parent == null)
root = y;
else if(n == n.parent.right)
n.parent.right = y;
else
n.parent.left = y;
y.right = n;
n.parent = y;
}
//Printing
public void printPreorder() {
printPreorder(root);
}
private void printPreorder(Node n) {
if(n == null) //nothing here
return;
System.out.print(n.data + " "); //print node data here
printPreorder(n.left);
printPreorder(n.right);
}
public void printInorder() {
printInorder(root);
}
private void printInorder(Node n) {
if(n == null) //nothing here
return;
printInorder(n.left);
System.out.print(n.data + " "); //print data here (in order)
printInorder(n.right);
}
public void printPostorder() {
printPostorder(root);
}
private void printPostorder(Node n) {
if(n == null)
return; //nothing here
printPostorder(n.left);
printPostorder(n.right);
//node is here so print data
System.out.print(n.data + " ");
}
}
quick messy main
public class MainBST {
public static void main(String args[]) {
BinarySearchTree BST = new BinarySearchTree();
//test run
BST.insertNode(8);
BST.insertNode(7);
BST.insertNode(5);
BST.insertNode(6);
BST.insertNode(3);
BST.insertNode(4);
System.out.print("Before rotation: \nPre-order: ");
BST.printPreorder();
System.out.print("\nIn-order: ");
BST.printInorder();
System.out.print("\nPost-order: ");
BST.printPostorder();
if(BST.search(5))
BST.rotateRight(BST.findNode(5));
System.out.print("\n\nAfter rotation: \nPre-order: ");
BST.printPreorder();
System.out.print("\nIn-order: ");
BST.printInorder();
System.out.print("\nPost-order: ");
BST.printPostorder();
}
}
The output:
Before rotation:
Pre-order: 8 7 5 3 4 6
In-order: 3 4 5 6 7 8
Post-order: 4 3 6 5 7 8
After rotation:
Pre-order: 8 7 3 5 4 6
In-order: 3 4 5 6 7 8
Post-order: 4 6 5 3 7 8
However this is the expected output after rotation (I have the right output for the tree before rotation):
Pre-order: 8 5 3 4 7 6
In-order: 3 4 5 6 7 8
Post-order: 4 3 6 7 5 8
It is clear there is some problem. Maybe it has to do with my wonky findNode() or the node structure? Or possibly even the rotation method has a problem. Can anyone help me out?
I want to solve the following task:
Given a singly linked list, write a function to swap elements
pairwise. For example, if the linked list is 1->2->3->4->5->6->7 then
the function should change it to 2->1->4->3->6->5->7, and if the
linked list is 1->2->3->4->5->6 then the function should change it to
2->1->4->3->6->5
To do so, I use recursive approach taken from here: http://www.geeksforgeeks.org/pairwise-swap-elements-of-a-given-linked-list-by-changing-links/ , namely, swap the first two nodes, and then recurse on the rest of the list. My function is the following:
private static ListNode reorder(ListNode l1) {
if(l1 == null || l1.next == null)
return l1;
ListNode rest = l1.next.next;
//change head
ListNode newHead = l1.next;
//change next of second node
newHead.next = l1;
l1.next = reorder(rest);
return newHead;
}
However on the input 1 2 3 4 5 6 I have output 1 4 3 6 5?! I debugged it but still can't see where is the problem. Can anyone explain me why this is the case? Here is the whole class:
public class Swap {
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public static void main(String[] args) {
ListNode l1 = new ListNode(1);
ListNode l2 = new ListNode(2);
ListNode l3 = new ListNode(3);
ListNode l4 = new ListNode(4);
ListNode l5 = new ListNode(5);
ListNode l6 = new ListNode(6);
ListNode l7 = new ListNode(7);
ListNode l8 = new ListNode(8);
ListNode l9 = new ListNode(9);
ListNode l10 = new ListNode(10);
l1.next = l2;
l2.next = l3;
l3.next = l4;
l4.next = l5;
l5.next = l6;
l7.next = l8;
l9.next = l10;
print(l1);
reorder(l1);
System.out.println();
print(l1);
}
private static void print(ListNode l1) {
ListNode current = l1;
while(current != null){
System.out.print(current.val + " ");
current = current.next;
}
}
private static ListNode reorder(ListNode l1) {
if(l1 == null || l1.next == null)
return l1;
ListNode rest = l1.next.next;
//change head
ListNode newHead = l1.next;
//change next of second node
newHead.next = l1;
l1.next = reorder(rest);
return newHead;
}
}
You're printing the list starting at l1, which is now the second element. You want to call
print(reorder(l1));
This is a recursive approach I did, it works for me. Let me know if there is any problem.
public void pairwiseSwap(Node node){
if(size() == 0){
System.out.println("empty");
return;
}
if(node.next == null){
System.out.println(node.value);
return;
}
Node one = node;
Node two = node.next;
System.out.println(two.value);
System.out.println(one.value);
if(two.next == null)
return;
pairwiseSwap(two.next);
}
your list is not well connected, you are missing these links:
l6.next = l7;
l8.next = l9;
Here is the solution for most f the linked list replated problems
Insert at Start
Insert at End
Insert at Position
Get the size of the list
Display the list
Delete from the list
Replace the node
Search item position in the list
Find the middle of the list"
Get the item from the last
Reverse the list
Swap the node of the list
Pairwise swap the list
Make the last node as the first node
Node.java
package com.practice.ds.list;
final public class Node<T> {
public Node<T> next = null;
public Node<T> prev = null;
public T data = null;
public Node() {
}
public Node(T data) {
this.data = data;
}
#Override
public String toString() {
return "Node [next=" + next + ", prev=" + prev + ", data=" + data + "]";
}
}
LinkedList.java
package com.practice.ds.list;
public class LinkedList<T> {
private Node<T> head = null;
private Node<T> tail = null;
public void insertAtStart(T data) {
throwEmptyDataException(data);
Node<T> node = new Node<T>(data);
if(empty()) {
head = node;
tail = head;
}else {
node.next = head;
head = node;
}
display();
}
public void insertAtEnd(T data) {
throwEmptyDataException(data);
if(empty()) {
insertAtStart(data);
}else {
Node<T> node = new Node<T>(data);
tail.next = node;
tail = node;
display();
}
}
public void insertAtPosition(int position, T data) {
throwEmptyDataException(data);
if (position < 1 || position > size() || empty())
throw new IllegalArgumentException("Can't perform insertion. Please check your inputs");
Node<T> node = head;
Node<T> tempNode = node;
for (int i = 1; i <= size(); i++) {
if (i == position) {
if (node == head) {
insertAtStart(data);
return;
} else {
Node<T> newNode = new Node<T>(data);
tempNode.next = newNode;
newNode.next = node;
display();
break;
}
}
tempNode = node;
node = node.next;
}
}
public boolean delete(int position) {
if (empty() || position < 1 || position > size())
return false;
Node<T> node = head;
Node<T> tempNode = node;
for (int i = 1; i <= size(); i++) {
if(i == position) {
if(node == head) {
head = head.next;
return true;
}else if(node == tail) {
tempNode.next = null;
tail = tempNode;
return true;
}else {
tempNode.next = node.next;
return true;
}
}
tempNode = node;
node = node.next;
}
return false;
}
public T replace(int position, T data) {
throwEmptyDataException(data);
if (empty() || position < 1 || position > size())
return null;
Node<T> node = head;
for (int i = 1; i <= size(); i++) {
if(i == position) {
T replaceData = node.data;
node.data = data;
return replaceData;
}
node = node.next;
}
return null;
}
public boolean search(T data) {
Node<T> node = head;
while(node != null && !node.data.equals(data)) {
node = node.next;
}
return node != null;
}
public T middle() {
Node<T> slowPtr = head;
Node<T> fastPtr = head;
while(fastPtr != null && fastPtr.next != null) {
slowPtr = slowPtr.next;
fastPtr = fastPtr.next.next;
}
return empty() ? null : slowPtr.data;
}
public T getElementFromLast(int position) {
if(empty() || position < 1 || position > getSizeIteratively())
return null;
Node<T> firstPtr = head;
Node<T> secondPtr = head;
for(int i = 1;i<=size();i++) {
if(i > position)
firstPtr = firstPtr.next;
if(secondPtr.next == null)
return firstPtr.data;
secondPtr = secondPtr.next;
}
return null;
}
public void reverse() {
Node<T> prev = null;
Node<T> current = head;
Node<T> next = null;
while(current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
swapHeadTail();
displayIteratively();
}
public void reverseRecursively() {
reverseRecursively(head);
swapHeadTail();
display();
}
private Node<T> reverseRecursively(Node<T> node) {
if(node == null || node.next == null)
return node;
Node<T> secondNode = node.next;
node.next = null;
Node<T> reverseRest = reverseRecursively(secondNode);
secondNode.next = node;
return reverseRest;
}
private void swapHeadTail() {
Node<T> temp = head;
head = tail;
tail = temp;
}
public void swapPairwise() {
if(empty())
return;
Node<T> firstNode = head;
Node<T> secondNode = firstNode.next;
while(firstNode != null && secondNode != null) {
swap(firstNode.data, secondNode.data);
firstNode = firstNode.next;
if(firstNode != null)
secondNode = firstNode.next;
}
}
public void swap(T firstData, T secondData) {
throwEmptyException();
throwEmptyDataException(firstData);
throwEmptyDataException(secondData);
if(firstData.equals(secondData))
throw new IllegalArgumentException(firstData +" & "+ secondData+" both are the same. Can't swap");
Node<T> firstDataPtr = head;
Node<T> prevfirstDataPtr = firstDataPtr;
while (firstDataPtr != null && !firstDataPtr.data.equals(firstData)) {
prevfirstDataPtr = firstDataPtr;
firstDataPtr = firstDataPtr.next;
}
Node<T> secondDataPtr = head;
Node<T> prevSecondDataPtr = secondDataPtr;
while (secondDataPtr!= null && !secondDataPtr.data.equals(secondData)) {
prevSecondDataPtr = secondDataPtr;
secondDataPtr = secondDataPtr.next;
}
if(!(firstDataPtr == null || secondDataPtr == null)) {
// either first node or second node is head node
if (firstDataPtr == head)
head = secondDataPtr;
else if (secondDataPtr == head)
head = firstDataPtr;
// either first node or second node is tail node
if (firstDataPtr == tail)
tail = secondDataPtr;
else if (secondDataPtr == tail)
tail = firstDataPtr;
// getting the next pointer of both nodes
Node<T> nextFirstDataPtr = firstDataPtr.next;
Node<T> nextSecondDataPtr = secondDataPtr.next;
// swapping the nodes
prevfirstDataPtr.next = secondDataPtr;
secondDataPtr.next = nextFirstDataPtr;
prevSecondDataPtr.next = firstDataPtr;
firstDataPtr.next = nextSecondDataPtr;
// checking if both node is adjacent node
// if both nodes are adjacent re-adjust the pointer
if(nextFirstDataPtr == secondDataPtr) {
secondDataPtr.next = firstDataPtr;
} else if(nextSecondDataPtr == firstDataPtr) {
firstDataPtr.next = secondDataPtr;
}
} else
throw new IllegalArgumentException("Either "+firstData+" or "+secondData+" not present in the list");
displayIteratively();
}
public void setLastNodeAsFirstNode() {
if(empty() || head.next == null) {
return;
}
Node<T> node = head;
Node<T> prevNode = node;
while (node.next != null) {
prevNode = node;
node = node.next;
}
node.next = head;
head = node;
prevNode.next = null;
tail = prevNode;
display();
}
public int getSizeIteratively() {
if (empty())
return 0;
int size = 0;
Node<T> node = head;
while (node != null) {
++size;
node = node.next;
}
return size;
}
public int size() {
return size(head, 0);
}
private int size(Node<T> node, int size) {
return node != null ? size(node.next, ++size) : size;
}
public void displayIteratively() {
Node<T> node = head;
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
public void display() {
display(head);
}
private void display(Node<T> node) {
if (node != null) {
System.out.print(node.data + " ");
display(node.next);
}
}
public void throwEmptyException() {
if (empty())
throw new IllegalArgumentException("List is empty!");
}
private void throwEmptyDataException(T data) {
if (data == null)
throw new IllegalArgumentException("data is null !");
}
public boolean empty() {
return head == null;
}
}
LinkedListTest.java
package com.practice.ds.list;
import java.util.Scanner;
public class LinkedListTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
LinkedList<Integer> list = new LinkedList<>();
boolean exit = false;
do {
System.out.println("\n----------------------------------------");
System.out.println("1. Insert at Start");
System.out.println("2. Insert at End");
System.out.println("3. Insert at Position");
System.out.println("4. Get the size of list");
System.out.println("5. Display the list");
System.out.println("6. Delete from the list ");
System.out.println("7. Replace the node ");
System.out.println("8. Search item position in the list ");
System.out.println("9. Find the middle of the list");
System.out.println("10. Get item from the last : ");
System.out.println("11. Reverse the list :: ");
System.out.println("12. Swap the node of the list");
System.out.println("13. Pairwise swap the list");
System.out.println("14. Make last node as first node");
System.out.println("15. Segregate even and odd node");
System.out.println();
int choice = scanner.nextInt();
switch (choice) {
case 1:
try {
System.out.println("Insert the node : ");
int node = scanner.nextInt();
list.insertAtStart(node);
} catch (Exception e) {
e.printStackTrace();
}
break;
case 2:
try {
System.out.println("Insert the node : ");
int node = scanner.nextInt();
list.insertAtEnd(node);
} catch (Exception e) {
e.printStackTrace();
}
break;
case 3:
try {
System.out.println("Enter the position :");
int position = scanner.nextInt();
System.out.println("Insert the node :");
int node = scanner.nextInt();
list.insertAtPosition(position, node);
} catch (Exception e) {
e.printStackTrace();
}
break;
case 4:
try {
System.out.println("Getting the size :: ");
System.out.println("1. Get Iteratively");
System.out.println("2. Get Recursively");
int input = scanner.nextInt();
switch (input) {
case 1:
System.out.println("The size of the list :: " + list.getSizeIteratively());
break;
case 2:
System.out.println("The size of the list :: " + list.size());
break;
default:
System.out.println("Invalid input...!");
break;
}
} catch (Exception e) {
e.printStackTrace();
}
break;
case 5:
try {
System.out.println("Displaying the list :: ");
System.out.println("1. Display Iteratively");
System.out.println("2. Display Recursively");
int input = scanner.nextInt();
switch (input) {
case 1:
list.displayIteratively();
break;
case 2:
list.display();
break;
default:
System.out.println("Invalid input...!");
break;
}
} catch (Exception e) {
e.printStackTrace();
}
break;
case 6:
try {
System.out.println("Enter the position ");
int position = scanner.nextInt();
System.out.println("is Delete :: " + list.delete(position));
} catch (Exception e) {
e.printStackTrace();
}
break;
case 7:
try {
System.out.println("Enter the position ");
int position = scanner.nextInt();
System.out.println("Insert the item ");
int data = scanner.nextInt();
list.replace(position, data);
} catch (Exception e) {
e.printStackTrace();
}
break;
case 8:
try {
System.out.println("Note: It will give first occurence of the item ");
System.out.println("Enter the item ");
int data = scanner.nextInt();
System.out.println(list.search(data));
} catch (Exception e) {
e.printStackTrace();
}
break;
case 9:
try {
System.out.println("The Middle node of the list is :: " + list.middle());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 10:
System.out.println("Enter the position ");
try {
int position = scanner.nextInt();
System.out.println("Element is :: " + list.getElementFromLast(position));
} catch (Exception e) {
e.printStackTrace();
}
break;
case 11:
System.out.println("Reversing the list...");
System.out.println("1. Iteratively");
System.out.println("2. Recursively");
int key = scanner.nextInt();
switch (key) {
case 1:
try {
list.reverse();
} catch (Exception e) {
e.printStackTrace();
}
break;
case 2:
try {
list.reverseRecursively();
} catch (Exception e) {
e.printStackTrace();
}
break;
default:
System.out.println("Your choice is out of the box...! \ntry again...");
break;
}
break;
case 12:
try {
System.out.println("Enter first node ");
int firstNode = scanner.nextInt();
System.out.println("Enter second node ");
int secondNode = scanner.nextInt();
list.swap(firstNode, secondNode);
} catch (Exception e) {
e.printStackTrace();
}
break;
case 13:
try {
list.swapPairwise();
} catch (Exception e) {
e.printStackTrace();
}
break;
case 14:
try {
list.setLastNodeAsFirstNode();
} catch (Exception e) {
e.printStackTrace();
}
break;
default:
System.out.println("Your choice is out of the box...! \ntry again...");
break;
}
} while (!exit);
scanner.close();
}
}
I am trying to implement BST algorithm using Cormen's pseudo code yet having issue.
Here is my Code for Node:
public class Node {
Node left;
Node right;
int value;
Node(int value){
this.value = value;
this.left = null;
this.right = null;
}
}
and for the Bstree:
public class Btree {
Node root;
Btree(){
this.root = null;
}
public static void inorderWalk(Node n){
if(n != null){
inorderWalk(n.left);
System.out.print(n.value + " ");
inorderWalk(n.right);
}
}
public static Node getParent(Btree t, Node n){
Node current = t.root;
Node parent = null;
while(true){
if (current == null)
return null;
if( current.value == n.value ){
break;
}
if (current.value > n.value){
parent = current;
current = current.left;
}
else{ //(current.value < n.value)
parent = current;
current = current.right;
}
}
return parent;
}
public static Node search(Node n,int key){
if(n == null || key == n.value ){
return n;
}
if(key < n.value){
return search(n.left,key);
}
else{
return search(n.right,key);
}
}
public static Node treeMinimum(Node x){
if(x == null){
return null;
}
while(x.left != null){
x = x.left;
}
return x;
}
public static Node treeMaximum(Node x){
if(x == null){
return null;
}
while(x.right != null){
x = x.right;
}
return x;
}
public static Node treeSuccessor(Btree t,Node x){
if (x.right == null){
return treeMinimum(x.right);
}
Node y = getParent(t,x);
while(y != null && x == y.right){
x = y;
y = getParent(t,y);
}
return y;
}
public static Btree insert(Btree t,Node z){
Node y = null;
Node x = t.root;
while(x != null){
y = x;
if(z.value < x.value)
x = x.left;
else
x = x.right;
}
Node tmp = getParent(t,z);
tmp = y;
if(y == null){
t.root = z;
}
else if(z.value < y.value)
y.left = z;
else
y.right = z;
return t;
}
public static Btree delete(Btree t,Node z){
Node y,x;
if (z.left == null || z.right == null)
y = z;
else
y = treeSuccessor(t,z);
if (y.left != null)
x = y.left;
else
x = y.right;
if (x != null){
Node tmp = getParent(t,x);
tmp = getParent(t,y);
}
if (getParent(t,y) == null ){
t.root = x;
}
else{
if( y == getParent(t,y).left ){
getParent(t,y).left = x;
}
else{
getParent(t,y).right = x;
}
}
if(y != z){
z.value = y.value;
}
return t;
}
public static void main(String[] args){
Btree test = new Btree();
Node n1 = new Node(6);
Node n2 = new Node(3);
Node n3 = new Node(9);
Node n4 = new Node(1);
Node n5 = new Node(16);
Node n6 = new Node(4);
Node n7 = new Node(2);
Node n8 = new Node(11);
Node n9 = new Node(13);
test = insert(test,n1);
test = insert(test,n2);
test = insert(test,n3);
test = insert(test,n4);
test = insert(test,n5);
test = insert(test,n6);
test = insert(test,n7);
test = insert(test,n8);
test = insert(test,n9);
inorderWalk(test.root);
System.out.println();
test = delete(test,n8);
inorderWalk(test.root);
System.out.println();
test = delete(test,n5);
inorderWalk(test.root);
System.out.println();
test = delete(test,n2);
inorderWalk(test.root);
System.out.println();
test = delete(test,n1);
inorderWalk(test.root);
}
}
The main problem is with the remove part, sometimes it is working as intended, sometimes removing wrongly and sometimes null pointer exception. What can be the issue ?
Ps: this is NOT a homework
Some immediate problems with your code: your treeSuccessor starts with
if (x.right == null){
return treeMinimum(x.right);
}
which should be if (x.right != null), of course.
Your insert code has the lines
Node tmp = getParent(t,z);
tmp = y;
where you assign to tmp and immediately assign to it again. It doesn't seem to me that you need these lines at all, since you don't use tmp further on. At this moment, you have y being the node to whose child z gets inserted, so just delete these lines.
Again, in delete, you have the lines
if (x != null){
Node tmp = getParent(t,x);
tmp = getParent(t,y);
}
where you don't actually do anything, since tmp is not visible outside this snippet. And further on, in delete, you repeat the expression getParent(t,y), which can be an expensive operation, so you should compute it only once and assign it to some variable.
But in general, your code, though it seems correct (probably apart from delete, which I did not understand completely but which looks suspicious), does not much resemble typical binary tree code. You don't really need the getParent and treeSuccessor methods to implement search, insert, and delete. The basic structure that you have for search works for the others too, with the following modifications:
with insert, when you get to a null link, instead of returning null, insert the element to that point
with delete, when you find the element, if it has only one (or no) child, replace it with that child, and if it has two children, replace it with either the maximum of the left child tree or the minimum of the right child tree
Both of these require in addition that you keep track of the parent node while descending into the tree, but that's the only modification you need to make to search. In particular, there is never any need to go upwards in the tree (which treeSuccessor will do).
First of all, your implementation got nothing to do with object orientation (except using objects). The insert and delete operations for example should operate ON the Tree.
Besides, I would recommend to implement the Node class as a static member of the Tree class.
public class Tree {
private Node root = null;
// remainder omitted
public boolean insert(int element) {
if (isEmpty()) {
root = new Node(element);
return true; // empty tree, Node could be inserted, return true
}
Node current = root; // start at root
Node parent; // the current Node's parent
do {
parent = current;
if (element < current.element) {
current = current.left; // go to left
} else if (element > current.element) {
current = current.right; // go to right
} else {
return false; // duplicates are NOT allowed, element could not be inserted -> return false
} while (current != null);
Node node = new Node(element);
if (element < current.element) {
parent.left = node;
} else {
parent.right = node;
}
return true; // node successfully inserted
}
public boolean isEmpty() {
return root == null;
}
private static class Node { // static member class
Node left = null;
Node right = null;
final int element;
Node(int element) {
this.element = element;
}
}
}
...what is up with your delete code? It doesn't make a lot of sense. I would consider rewriting it in a more logical way. Without the meaningless single-letter variable names. And add comments!
One possible algorithm is:
Get the parent of the node to delete
Get the right-most node of the left subtree, or the leftmost node of the right subtree
Remove the node to delete and replace it with the node you found
Rebalance the tree
...or, if you want to hack up this stuff so it's right, I'd start looking at the
if (x != null){
Node tmp = getParent(t,x);
tmp = getParent(t,y);
}
part, because that's clearly wrong.
I'll have to side with Anon and go for the rewrite. The null pointers come from your getParent function (which explicitly returns nulls along other things). So I would start there and fix the function(s) so that they return one thing and one thing only at the end of the function.
Here is the complete Implementation of Binary Search Tree In Java
insert,search,countNodes,traversal,delete,empty,maximum & minimum node,find parent node,print all leaf node, get level,get height, get depth,print left view, mirror view
import java.util.NoSuchElementException;
import java.util.Scanner;
import org.junit.experimental.max.MaxCore;
class BSTNode {
BSTNode left = null;
BSTNode rigth = null;
int data = 0;
public BSTNode() {
super();
}
public BSTNode(int data) {
this.left = null;
this.rigth = null;
this.data = data;
}
#Override
public String toString() {
return "BSTNode [left=" + left + ", rigth=" + rigth + ", data=" + data + "]";
}
}
class BinarySearchTree {
BSTNode root = null;
public BinarySearchTree() {
}
public void insert(int data) {
BSTNode node = new BSTNode(data);
if (root == null) {
root = node;
return;
}
BSTNode currentNode = root;
BSTNode parentNode = null;
while (true) {
parentNode = currentNode;
if (currentNode.data == data)
throw new IllegalArgumentException("Duplicates nodes note allowed in Binary Search Tree");
if (currentNode.data > data) {
currentNode = currentNode.left;
if (currentNode == null) {
parentNode.left = node;
return;
}
} else {
currentNode = currentNode.rigth;
if (currentNode == null) {
parentNode.rigth = node;
return;
}
}
}
}
public int countNodes() {
return countNodes(root);
}
private int countNodes(BSTNode node) {
if (node == null) {
return 0;
} else {
int count = 1;
count += countNodes(node.left);
count += countNodes(node.rigth);
return count;
}
}
public boolean searchNode(int data) {
if (empty())
return empty();
return searchNode(data, root);
}
public boolean searchNode(int data, BSTNode node) {
if (node != null) {
if (node.data == data)
return true;
else if (node.data > data)
return searchNode(data, node.left);
else if (node.data < data)
return searchNode(data, node.rigth);
}
return false;
}
public boolean delete(int data) {
if (empty())
throw new NoSuchElementException("Tree is Empty");
BSTNode currentNode = root;
BSTNode parentNode = root;
boolean isLeftChild = false;
while (currentNode.data != data) {
parentNode = currentNode;
if (currentNode.data > data) {
isLeftChild = true;
currentNode = currentNode.left;
} else if (currentNode.data < data) {
isLeftChild = false;
currentNode = currentNode.rigth;
}
if (currentNode == null)
return false;
}
// CASE 1: node with no child
if (currentNode.left == null && currentNode.rigth == null) {
if (currentNode == root)
root = null;
if (isLeftChild)
parentNode.left = null;
else
parentNode.rigth = null;
}
// CASE 2: if node with only one child
else if (currentNode.left != null && currentNode.rigth == null) {
if (root == currentNode) {
root = currentNode.left;
}
if (isLeftChild)
parentNode.left = currentNode.left;
else
parentNode.rigth = currentNode.left;
} else if (currentNode.rigth != null && currentNode.left == null) {
if (root == currentNode)
root = currentNode.rigth;
if (isLeftChild)
parentNode.left = currentNode.rigth;
else
parentNode.rigth = currentNode.rigth;
}
// CASE 3: node with two child
else if (currentNode.left != null && currentNode.rigth != null) {
// Now we have to find minimum element in rigth sub tree
// that is called successor
BSTNode successor = getSuccessor(currentNode);
if (currentNode == root)
root = successor;
if (isLeftChild)
parentNode.left = successor;
else
parentNode.rigth = successor;
successor.left = currentNode.left;
}
return true;
}
private BSTNode getSuccessor(BSTNode deleteNode) {
BSTNode successor = null;
BSTNode parentSuccessor = null;
BSTNode currentNode = deleteNode.left;
while (currentNode != null) {
parentSuccessor = successor;
successor = currentNode;
currentNode = currentNode.left;
}
if (successor != deleteNode.rigth) {
parentSuccessor.left = successor.left;
successor.rigth = deleteNode.rigth;
}
return successor;
}
public int nodeWithMinimumValue() {
return nodeWithMinimumValue(root);
}
private int nodeWithMinimumValue(BSTNode node) {
if (node.left != null)
return nodeWithMinimumValue(node.left);
return node.data;
}
public int nodewithMaximumValue() {
return nodewithMaximumValue(root);
}
private int nodewithMaximumValue(BSTNode node) {
if (node.rigth != null)
return nodewithMaximumValue(node.rigth);
return node.data;
}
public int parent(int data) {
return parent(root, data);
}
private int parent(BSTNode node, int data) {
if (empty())
throw new IllegalArgumentException("Empty");
if (root.data == data)
throw new IllegalArgumentException("No Parent node found");
BSTNode parent = null;
BSTNode current = node;
while (current.data != data) {
parent = current;
if (current.data > data)
current = current.left;
else
current = current.rigth;
if (current == null)
throw new IllegalArgumentException(data + " is not a node in tree");
}
return parent.data;
}
public int sibling(int data) {
return sibling(root, data);
}
private int sibling(BSTNode node, int data) {
if (empty())
throw new IllegalArgumentException("Empty");
if (root.data == data)
throw new IllegalArgumentException("No Parent node found");
BSTNode cureent = node;
BSTNode parent = null;
boolean isLeft = false;
while (cureent.data != data) {
parent = cureent;
if (cureent.data > data) {
cureent = cureent.left;
isLeft = true;
} else {
cureent = cureent.rigth;
isLeft = false;
}
if (cureent == null)
throw new IllegalArgumentException("No Parent node found");
}
if (isLeft) {
if (parent.rigth != null) {
return parent.rigth.data;
} else
throw new IllegalArgumentException("No Sibling is there");
} else {
if (parent.left != null)
return parent.left.data;
else
throw new IllegalArgumentException("No Sibling is there");
}
}
public void leafNodes() {
if (empty())
throw new IllegalArgumentException("Empty");
leafNode(root);
}
private void leafNode(BSTNode node) {
if (node == null)
return;
if (node.rigth == null && node.left == null)
System.out.print(node.data + " ");
leafNode(node.left);
leafNode(node.rigth);
}
public int level(int data) {
if (empty())
throw new IllegalArgumentException("Empty");
return level(root, data, 1);
}
private int level(BSTNode node, int data, int level) {
if (node == null)
return 0;
if (node.data == data)
return level;
int result = level(node.left, data, level + 1);
if (result != 0)
return result;
result = level(node.rigth, data, level + 1);
return result;
}
public int depth() {
return depth(root);
}
private int depth(BSTNode node) {
if (node == null)
return 0;
else
return 1 + Math.max(depth(node.left), depth(node.rigth));
}
public int height() {
return height(root);
}
private int height(BSTNode node) {
if (node == null)
return 0;
else
return 1 + Math.max(height(node.left), height(node.rigth));
}
public void leftView() {
leftView(root);
}
private void leftView(BSTNode node) {
if (node == null)
return;
int height = height(node);
for (int i = 1; i <= height; i++) {
printLeftView(node, i);
}
}
private boolean printLeftView(BSTNode node, int level) {
if (node == null)
return false;
if (level == 1) {
System.out.print(node.data + " ");
return true;
} else {
boolean left = printLeftView(node.left, level - 1);
if (left)
return true;
else
return printLeftView(node.rigth, level - 1);
}
}
public void mirroeView() {
BSTNode node = mirroeView(root);
preorder(node);
System.out.println();
inorder(node);
System.out.println();
postorder(node);
System.out.println();
}
private BSTNode mirroeView(BSTNode node) {
if (node == null || (node.left == null && node.rigth == null))
return node;
BSTNode temp = node.left;
node.left = node.rigth;
node.rigth = temp;
mirroeView(node.left);
mirroeView(node.rigth);
return node;
}
public void preorder() {
preorder(root);
}
private void preorder(BSTNode node) {
if (node != null) {
System.out.print(node.data + " ");
preorder(node.left);
preorder(node.rigth);
}
}
public void inorder() {
inorder(root);
}
private void inorder(BSTNode node) {
if (node != null) {
inorder(node.left);
System.out.print(node.data + " ");
inorder(node.rigth);
}
}
public void postorder() {
postorder(root);
}
private void postorder(BSTNode node) {
if (node != null) {
postorder(node.left);
postorder(node.rigth);
System.out.print(node.data + " ");
}
}
public boolean empty() {
return root == null;
}
}
public class BinarySearchTreeTest {
public static void main(String[] l) {
System.out.println("Weleome to Binary Search Tree");
Scanner scanner = new Scanner(System.in);
boolean yes = true;
BinarySearchTree tree = new BinarySearchTree();
do {
System.out.println("\n1. Insert");
System.out.println("2. Search Node");
System.out.println("3. Count Node");
System.out.println("4. Empty Status");
System.out.println("5. Delete Node");
System.out.println("6. Node with Minimum Value");
System.out.println("7. Node with Maximum Value");
System.out.println("8. Find Parent node");
System.out.println("9. Count no of links");
System.out.println("10. Get the sibling of any node");
System.out.println("11. Print all the leaf node");
System.out.println("12. Get the level of node");
System.out.println("13. Depth of the tree");
System.out.println("14. Height of Binary Tree");
System.out.println("15. Left View");
System.out.println("16. Mirror Image of Binary Tree");
System.out.println("Enter Your Choice :: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
try {
System.out.println("Enter Value");
tree.insert(scanner.nextInt());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 2:
System.out.println("Enter the node");
System.out.println(tree.searchNode(scanner.nextInt()));
break;
case 3:
System.out.println(tree.countNodes());
break;
case 4:
System.out.println(tree.empty());
break;
case 5:
try {
System.out.println("Enter the node");
System.out.println(tree.delete(scanner.nextInt()));
} catch (Exception e) {
System.out.println(e.getMessage());
}
case 6:
try {
System.out.println(tree.nodeWithMinimumValue());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 7:
try {
System.out.println(tree.nodewithMaximumValue());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 8:
try {
System.out.println("Enter the node");
System.out.println(tree.parent(scanner.nextInt()));
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 9:
try {
System.out.println(tree.countNodes() - 1);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 10:
try {
System.out.println("Enter the node");
System.out.println(tree.sibling(scanner.nextInt()));
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 11:
try {
tree.leafNodes();
} catch (Exception e) {
System.out.println(e.getMessage());
}
case 12:
try {
System.out.println("Enter the node");
System.out.println("Level is : " + tree.level(scanner.nextInt()));
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 13:
try {
System.out.println(tree.depth());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 14:
try {
System.out.println(tree.height());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 15:
try {
tree.leftView();
System.out.println();
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 16:
try {
tree.mirroeView();
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
default:
break;
}
tree.preorder();
System.out.println();
tree.inorder();
System.out.println();
tree.postorder();
} while (yes);
scanner.close();
}
}
As per my understanding following implementation done for binary search tree, kindly look
into that and let me know any feedback required
Insertion
InOrderTraversal
Search
Removal
Please take a look at the main method. so, Please provide your's feedback to improve further from my side.
public class BinarySearchTree {
private Node root;
public BinarySearchTree() {
root = null;
}
public BinarySearchTree(int rootData) {
root = new Node(rootData);
}
public void insertElement(int element,Node parent) {
Node temp = root;
if(parent!=null) temp = parent;
if(temp!=null) {
Node node = new Node(element);
if(element<temp.getData()) {
if(temp.getLeft()!=null)
insertElement(element, temp.getLeft());
else
temp.setLeft(node);
}else if(element>temp.getData()) {
if(temp.getRight()!=null)
insertElement(element, temp.getRight());
else
temp.setRight(node);
}
}
}
public void traverseInOrder() {
if(root!=null) {
traverse(root.getLeft());
System.out.println(root.getData());
traverse(root.getRight());
}
}
public void traverse(Node temp) {
if(temp!=null) {
traverse(temp.getLeft());
System.out.println(temp.getData());
traverse(temp.getRight());
}
}
public int searchElement(int element,Node node) {
Node temp = root;
if(node!=null) temp = node;
if(temp!=null) {
if(temp.getData()<element) {
if(temp.getRight()!=null)
return searchElement(element, temp.getRight());
}else if(temp.getData()>element) {
if(temp.getLeft()!=null)
return searchElement(element,temp.getLeft());
}else if(temp.getData()==element){
return temp.getData();
}
}
return -1;
}
public void remove(int element,Node node,Node predecer) {
Node temp = root;
if(node!=null) temp = node;
if(temp!=null) {
if(temp.getData()>element) {
remove(element, temp.getLeft(), temp);
}else if(temp.getData()<element) {
remove(element, temp.getRight(), temp);
}else if(element==temp.getData()) {
if(temp.getLeft()==null && temp.getRight()==null) {
if(predecer.getData()>temp.getData()) {
predecer.setLeft(null);
}else if(predecer.getData()<temp.getData()) {
predecer.setRight(null);
}
}else if(temp.getLeft()!=null && temp.getRight()==null) {
predecer.setRight(temp.getLeft());
}else if(temp.getLeft()==null && temp.getRight()!=null) {
predecer.setLeft(temp.getRight());
}else if(temp.getLeft()!=null && temp.getRight()!=null) {
Node leftMostElement = findMaximumLeft(temp.getLeft());
if(leftMostElement!=null) {
remove(leftMostElement.getData(), temp, temp);
temp.setData(leftMostElement.getData());
}
}
}
}
}
public Node findMaximumLeft(Node parent) {
Node temp = parent;
if(temp.getRight()!=null)
return findMaximumLeft(temp.getRight());
else
return temp;
}
public static void main(String[] args) {
BinarySearchTree bs = new BinarySearchTree(10);
bs.insertElement(29, null);
bs.insertElement(19, null);
bs.insertElement(209, null);
bs.insertElement(6, null);
bs.insertElement(7, null);
bs.insertElement(17, null);
bs.insertElement(37, null);
bs.insertElement(67, null);
bs.insertElement(-7, null);
bs.remove(6, null, null);
bs.traverseInOrder();}}