Finding a node in a binary search tree in java? - java

I am trying to write a method that returns the depth of a target int in a binary search tree. Right now it works for some smaller trees, but not always. Does anyone see where I may be going wrong?
static int count=1;
public static int findDepth(TreeNode<Integer> root, int target)
// pre: 0 or more elements in the tree, integer to search for
// post: return depth of target if found, -1 otherwise
{
count++;
if (root!=null)
{
if (root.getValue()<target)
{
if (root.getValue()==target)
{System.out.println(count);
return count;}
else
{findDepth(root.getLeft(), target);
count--;
findDepth(root.getRight(), target);
}
}
else if (root.getValue()>target)
{
if (root.getValue()==target)
{System.out.println(count);
return count;}
else
{findDepth(root.getLeft(), target);
count--;
findDepth(root.getRight(), target);
}
}
else if (root.getValue()==target)
return 1;
else
return -1;
}
return count;
}

There's a few things wrong.
It will never get into this case:
if (root.getValue()<target)
{
if (root.getValue()==target)
{System.out.println(count);
return count;}
Also it will never get into this case:
else if (root.getValue()>target)
{
if (root.getValue()==target)
{System.out.println(count);
return count;}
The biggest issue is that you're keeping a global static count, and recursively going through both left and right paths.
First of all, for a BST, there is no need to go both left and right.
Second, it's better to pass the count through a parameter rather than keeping a global.
Rather than fix your code, I'll post this working example for you to use as a reference:
public class Main
{
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.add(20);
tree.add(10);
tree.add(30);
tree.add(15);
tree.add(25);
tree.add(5);
tree.add(35);
tree.add(1);
tree.add(6);
tree.add(14);
tree.add(16);
tree.add(24);
tree.add(26);
tree.add(34);
tree.add(36);
int level = tree.getLevel(6);
System.out.println(level);
}
}
public class TreeNode
{
int data;
TreeNode left;
TreeNode right;
public TreeNode(int d){
data = d;
left = null;
right = null;
}
}
public class BinaryTree
{
TreeNode root;
public BinaryTree(){
root = null;
}
public int getLevel(int val) {
if (root == null) return 0;
return getLevelHelper(root, val, 0);
}
public int getLevelHelper(TreeNode node, int val, int level){
int retVal = -1;
if (node.data == val){
return level;
}
if (val < node.data && node.left != null){
retVal = getLevelHelper(node.left, val, level + 1);
}
else if (val > node.data && node.right != null){
retVal = getLevelHelper(node.right, val, level + 1);
}
return retVal;
}
public boolean add(int newData){
if (root == null){
root = new TreeNode(newData);
return true;
}
else{
TreeNode curr = root;
while (true){
if (curr.data == newData){
return false;
}
else if (curr.data > newData){
if (curr.left == null){
curr.left = new TreeNode(newData);
return true;
}
else{
curr = curr.left;
}
}
else{
if (curr.right == null){
curr.right = new TreeNode(newData);
return true;
}
else{
curr = curr.right;
}
}
}
}
}
}

Related

Finding the oldest element in a min priority queue java

I am supposed to return the oldest element in a priority min queue along with said element. I have to use nodes, arrays are optional. This is what I got so far but I have an null pointer error on line 20 and i don't know how to fix it. Please help
public class MinHeap {
public static int timeStamp = 0;
public static int ts = 0;
public static int maxTime = 0;
public static Node root;
public MinHeap(){
this.root = null;
}
public static void insert(int id, int ts){
timeStamp++;
Node newNode = new Node(id);
if(root==null){
root = newNode;
}
Node current = root;
Node parent = null;
while(true){
parent = current;
if(id < current.data){
current = current.left;
if(current==null){
parent.left = newNode;
}
}else{
current = current.right;
if(current==null){
parent.right = newNode;
}
}
}
}
public static Node delete(int x, Node n){
timeStamp++;
if(n==null)
return n;
if(x == n.data){
if(n.left == null && n.right == null){
return null;
}else if(n.left == null){
n.right = delete(x, n.right);
return n;
}else if(n.right == null){
n.left = delete(x, n.left);
return n;
}else{
Node tempNode = findMin(n.right);
n.right = delete(tempNode.data, n.right);
n.data = tempNode.data;
return n;
}
}
if(x < n.data){
n.left = delete(x, n.left);
return n;
}else{
n.right = delete(x, n.right);
return n;
}
}
public static void display(Node root){
if(root!=null){
display(root.left);
System.out.print(" " + root.data);
display(root.right);
}
}
public static Node findMin(Node n){
if(n == null){
return null;
}
if(n.left == null){
return n;
}
return findMin(n.left);
}
public static int maxAge(){
int currentAge = 0;
currentAge = timeStamp - ts;
if(currentAge > maxTime)
maxTime = currentAge;
return maxTime;
}
public static void main(String [] arg){
MinHeap min = new MinHeap();
min.insert(1, ts = 0);
min.insert(2, ts = 1);
min.insert(3, ts = 2);
min.insert(4, ts = 4);
min.delete(1, root);
min.delete(2, root);
min.delete(3, root);
min.delete(4, root);
min.maxAge();
}
}
class Node{
int data;
Node left;
Node right;
public Node(int data){
this.data = data;
left = null;
right = null;
}
}
Your insert is broken. You forgot to break after finding the insert point, and you're not checking for the case where the key is already in the tree.
while (true) {
parent = current;
if (id < current.data) {
current = current.left;
if (current == null) {
parent.left = newNode;
// Break after insert
break;
}
} else if (id > current.data) {
current = current.right;
if (current == null) {
parent.right = newNode;
// Break after insert
break;
}
} else {
// Key exists.
break;
}
}

Deleting a node at a given index in Java; What am I doing wrong?

I have been stuck for the last 40-so minutes on this problem. I'm unsure of what I am doing wrong here, I have tried debugging many times and have read similar Q/A's. Can't figure it out and my assignment is due at midnight.
It is not deleting the Node.. None at all in fact. If the code seems right, then the problem may be lying inside main. Let me know, please & thank you!
Any help is well appreciated! :)
Problem Method Below
void deleteAtIndex(int idx)
{
if (length() >= idx)
{
if(idx == 0)
{
head = head.getNext();
}
else
{
Node temp = findAtIndex(idx-1);
temp.setNext(temp.getNext().getNext());
}
}
else
System.out.println("Invalid position");
}
Full Class Code Below
public class ShapeLinkedList {
public Node head; // Head is first node in linked list
public ShapeLinkedList() { }
public ShapeLinkedList(Node head) {
}
public boolean isEmpty() {
return length() == 0;
}
public void insertAtEnd(Shape data) {
Node end = new Node(data, null);
if (head == null)
head.setNext(end);
else
tail().setNext(end);
}
public void insertAtBeginning(Shape data) {
if (data != null)
{
Node temp = new Node(data, head);
head = temp;
}
}
public Node tail() {
if (head == null){
return null;
}
else
{
Node temp = head;
while(temp.getNext() != null){
temp = temp.getNext();
}
return temp;
}
}
public int length() { // 1
Node temp = head;
if (temp == null)
return 0;
int tempIndex = 0;
while(temp.getNext() != null){
temp = temp.getNext();
tempIndex++;
}
return tempIndex;
}
void insertAtIndex(int idx, Shape data) { //3
if (length() >= idx)
{
Node current = new Node(data, null);
Node temp = findAtIndex(idx);
current.setNext(temp.getNext());
temp.setNext(current);
}
}
Node findAtIndex(int idx) { // 2
if (length() >= idx)
{
Node temp = head;
for(int i = 0; i < idx; i++)
{
temp = temp.getNext();
}
return temp;
}
else
return null;
}
void deleteAtIndex(int idx) { //4
if (length() >= idx)
{
if(idx == 0)
{
head = head.getNext();
}
else
{
Node temp = findAtIndex(idx-1);
temp.setNext(temp.getNext().getNext());
}
}
else
System.out.println("Invalid position");
}
#Override
public String toString() {
return "";
}
void deleteData(Shape s) {
Node temp = head;
for(int i = 0; i < length(); i++)
{
if(temp.getData() == s)
deleteAtIndex(i);
}
}
#Override
public int hashCode() {
return 0;
}
#Override
public boolean equals(Object obj) {
return false;
}
// Node is nested class because it only exists along with linked list
public static class Node {
private Shape data;
private Node next;
public Node(Shape S, Node N){
data = S;
next = N;
}
public Node getNext(){
return next;
}
public Shape getData() { return data; }
public void setNext(Node N) { next = N; }
// TODO develop all the methods that are needed
// such as constructors, setters, getters
// toString, equals, hashCode
}
}
You have multiple bugs in your class. I guess if you fix them, your code will work fine. SO is not a debugging platform, thus your question is off-topic and you should learn using a debugger.
Here some issues I instantly have seen from a quick look at your code, I'm sure there are more issues:
if (length() >= idx) should probably be if (length() > idx) at all places and
if (head == null) head.setNext(end); should probably be if (head == null) head = end; and
public ShapeLinkedList(Node head) { } should probably be public ShapeLinkedList(Node head) { this.head = head; } and
int tempIndex = 0 should probably be int tempIndex = 1

return statement not returning control to caller in java

I am trying to practice binary trees in Java and tried to write a "isPresent" function. But the function isn't working if the argument (testInt) isn't the root node value. It is entering an infinite loop. I'm missing some silly thing I'm sure.
public class Node {
// Attributes
int value;
Node leftChild;
Node rightChild;
// Constructor
Node (int value) {
this.value = value;
}
// Getter
int getValue() {
return value;
}
boolean isPresent(int testInt) {
Node presentNode = this;
while (presentNode != null) {
if (presentNode.getValue() == testInt) {
return true;
} else if (testInt < presentNode.getValue()) {
presentNode.leftChild.isPresent(testInt);
} else {
presentNode.rightChild.isPresent(testInt);
}
}
return false;
}
}
public static void main(String args[]) {
int[] integers = new int[size];
Arrays.sort(integers);
Node binarySearchTree = createBSTFromSortedArray(integers, 0, size - 1);
if (binarySearchTree.isPresent(testInt)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
in.close();
}
private static Node createBSTFromSortedArray(int[] integers, int start, int end) {
if (end < start) {
return null;
}
int mid = (start + end) / 2;
Node binarySearchTree = new Node(integers[mid]);
binarySearchTree.leftChild = createBSTFromSortedArray(integers, start, mid - 1);
binarySearchTree.rightChild = createBSTFromSortedArray(integers, mid + 1, end);
return binarySearchTree;
}
In your isPresent method, you are ignoring the results of calling isPresent on the left and right children. Assign the left or right child to presentNode as appropriate.
Change
} else if (testInt < presentNode.getValue()) {
presentNode.leftChild.isPresent(testInt);
} else {
presentNode.rightChild.isPresent(testInt);
}
to
} else if (testInt < presentNode.getValue()) {
presentNode = presentNode.leftChild;
} else {
presentNode = presentNode.rightChild;
}

Recursively find nth to last element in linked list

I'm practicing basic data structure stuff and I'm having some difficulties with recursion. I understand how to do this through iteration but all of my attempts to return the nth node from the last of a linked list via recursion result in null. This is my code so far:
public static int i = 0;
public static Link.Node findnthToLastRecursion(Link.Node node, int pos) {
if(node == null) return null;
else{
findnthToLastRecursion(node.next(), pos);
if(++i == pos) return node;
return null;
}
Can anyone help me understand where I'm going wrong here?
This is my iterative solution which works fine, but I'd really like to know how to translate this into recursion:
public static Link.Node findnthToLast(Link.Node head, int n) {
if (n < 1 || head == null) {
return null;
}
Link.Node pntr1 = head, pntr2 = head;
for (int i = 0; i < n - 1; i++) {
if (pntr2 == null) {
return null;
} else {
pntr2 = pntr2.next();
}
}
while (pntr2.next() != null) {
pntr1 = pntr1.next();
pntr2 = pntr2.next();
}
return pntr1;
}
You need to go to the end and then count your way back, make sure to pass back the node each time its passed back. I like one return point
public static int i = 0;
public static Link.Node findnthToLastRecursion(Link.Node node, int pos) {
Link.Node result = node;
if(node != null) {
result = findnthToLastRecursion(node.next, pos);
if(i++ == pos){
result = node;
}
}
return result;
}
Working example outputs 7 as 2 away from the 9th and last node:
public class NodeTest {
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
/**
* #param args
*/
public static void main(String[] args) {
Node first = null;
Node prev = null;
for (int i = 0; i < 10; i++) {
Node current = new Node(prev, Integer.toString(i),null);
if(i==0){
first = current;
}
if(prev != null){
prev.next = current;
}
prev = current;
}
System.out.println( findnthToLastRecursion(first,2).item);
}
public static int i = 0;
public static Node findnthToLastRecursion(Node node, int pos) {
Node result = node;
if (node != null) {
result = findnthToLastRecursion(node.next, pos);
if (i++ == pos) {
result = node;
}
}
return result;
}
}
No need for static variables.
public class List {
private Node head = null;
// [...] Other methods
public Node findNthLastRecursive(int nth) {
if (nth <= 0) return null;
return this.findNthLastRecursive(this.head, nth, new int[] {0});
}
private Node findNthLastRecursive(Node p, int nth, int[] pos) {
if (p == null) {
return null;
}
Node n = findNthLastRecursive(p.next, nth, pos);
pos[0]++;
if (pos[0] == nth) {
n = p;
}
return n;
}
}
You can do this a couple of ways:
recurse through the list once to find the list length, then write a recursive method to return the kth element (a much easier problem).
use an auxiliary structure to hold the result plus the remaining length; this essentially replaces the two recursions of the first option with a single recursion:
static class State {
Link.Node result;
int trailingLength;
}
public static Link.Node findnthToLastRecursion(Link.Node node, int pos) {
if(node == null) return null;
State state = new State();
findnthToLastRecursion(node, pos, state);
return state.result;
}
private static void findnthToLastRecursion(Link.Node node, int pos, State state) {
if (node == null) {
state.trailingLength = 0;
} else {
findnthToLastRecursion(node.next(), state);
if (pos == state.trailingLength) {
state.result = node;
}
++state.trailingLength;
}
}
I misunderstood the question. Here is an answer based on your iterative solution:
public static Link.Node findnthToLast(Link.Node head, int n) {
return findnthToLastHelper(head, head, n);
}
private static Link.Node findnthToLastHelper(Link.Node head, Link.Node end, int n) {
if ( end == null ) {
return ( n > 0 ? null : head);
} elseif ( n > 0 ) {
return findnthToLastHelper(head, end.next(), n-1);
} else {
return findnthToLastHelper(head.next(), end.next(), 0);
}
}
actually you don't need to have public static int i = 0; . for utill method the pos is :
pos = linked list length - pos from last + 1
public static Node findnthToLastRecursion(Node node, int pos) {
if(node ==null){ //if null then return null
return null;
}
int length = length(node);//find the length of the liked list
if(length < pos){
return null;
}
else{
return utill(node, length - pos + 1);
}
}
private static int length(Node n){//method which finds the length of the linked list
if(n==null){
return 0;
}
int count = 0;
while(n!=null){
count++;
n=n.next;
}
return count;
}
private static Node utill(Node node, int pos) {
if(node == null) {
return null;
}
if(pos ==1){
return node;
}
else{
return utill(node.next, pos-1);
}
}
Here node.next is the next node. I am directly accessing the next node rather than calling the next() method. Hope it helps.
This cheats (slightly) but it looks good.
public class Test {
List<String> list = new ArrayList<> (Arrays.asList("Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten"));
public static String findNthToLastUsingRecursionCheatingALittle(List<String> list, int n) {
int s = list.size();
return s > n
// Go deeper!
? findNthToLastUsingRecursionCheatingALittle(list.subList(1, list.size()), n)
// Found it.
: s == n ? list.get(0)
// Too far.
: null;
}
public void test() {
System.out.println(findNthToLastUsingRecursionCheating(list,3));
}
public static void main(String args[]) {
new Test().test();
}
}
It prints:
Eight
which I suppose is correct.
I have use List instead of some LinkedList variant because I do not want to reinvent anything.
int nthNode(struct Node* head, int n)
{
if (head == NULL)
return 0;
else {
int i;
i = nthNode(head->left, n) + 1;
printf("=%d,%d,%d\n", head->data,i,n);
if (i == n)
printf("%d\n", head->data);
}
}
public class NthElementFromLast {
public static void main(String[] args) {
List<String> list = new LinkedList<>();
Stream.of("A","B","C","D","E").forEach(s -> list.add(s));
System.out.println(list);
System.out.println(getNthElementFromLast(list,2));
}
private static String getNthElementFromLast(List list, int positionFromLast) {
String current = (String) list.get(0);
int index = positionFromLast;
ListIterator<String> listIterator = list.listIterator();
while(positionFromLast>0 && listIterator.hasNext()){
positionFromLast--;
current = listIterator.next();
}
if(positionFromLast != 0) {
return null;
}
String nthFromLast = null;
ListIterator<String> stringListIterator = list.listIterator();
while(listIterator.hasNext()) {
current = listIterator.next();
nthFromLast = stringListIterator.next();
}
return nthFromLast;
}
}
This will find Nth element from last.
My approach is simple and straight,you can change the array size depending upon your requirement:
int pos_from_tail(node *k,int n)
{ static int count=0,a[100];
if(!k) return -1;
else
pos_from_tail(k->next,n);
a[count++]=k->data;
return a[n];
}
You'll have make slight changes in the code:
public static int i = 0;
public static Link.Node findnthToLastRecursion(Link.Node node, int pos) {
if(node == null) return null;
else{
**Link.Node temp = findnthToLastRecursion(node.next(), pos);
if(temp!=null)
return temp;**
if(++i == pos) return node;
return null;
}
}

binary search tree impelementation and java

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();}}

Categories