binary search tree deletion method [duplicate] - java

I am trying to implement a remove method for the BST structure that I have been working on. Here is the code with find, insert, and remove methods:
public class BST {
BSTNode root = new BSTNode("root");
public void insert(BSTNode root, String title){
if(root.title!=null){
if(title==root.title){
//return already in the catalog
}
else if(title.compareTo(root.title)<0){
if(root.leftChild==null){
root.leftChild = new BSTNode(title);
}
else{
insert(root.leftChild,title);
}
}
else if(title.compareTo(root.title)>0){
if(root.rightChild==null){
root.rightChild = new BSTNode(title);
}
else{
insert(root.rightChild,title);
}
}
}
}
public void find(BSTNode root, String title){
if(root!= null){
if(title==root.title){
//return(true);
}
else if(title.compareTo(root.title)<0){
find(root.leftChild, title);
}
else{
find(root.rightChild, title);
}
}
else{
//return false;
}
}
public void remove(BSTNode root, String title){
if(root==null){
return false;
}
if(title==root.title){
if(root.leftChild==null){
root = root.rightChild;
}
else if(root.rightChild==null){
root = root.leftChild;
}
else{
//code if 2 chlidren remove
}
}
else if(title.compareTo(root.title)<0){
remove(root.leftChild, title);
}
else{
remove(root.rightChild, title);
}
}
}
I was told that I could use the insert method to help me with the remove method, but I am just not seeing how I can grab the smallest/largest element, and then replace the one I am deleting with that value, then recursively delete the node that I took the replacement value, while still maintaining O(logn) complexity. Anyone have any ideas or blatant holes I missed, or anything else helpful as I bang my head about this issue?
EDIT:
I used the answers ideas to come up with this, which I believe will work but I'm getting an error that my methods (not just the remove) must return Strings, here is what the code looks like, I thought that's the return statements??
public String remove(BSTNode root, String title){
if(root==null){
return("empty root");
}
if(title==root.title){
if(root.leftChild==null){
if(root.rightChild==null){
root.title = null;
return(title+ "was removed");
}
else{
root = root.rightChild;
return(title+ "was removed");
}
}
else if(root.rightChild==null){
root = root.leftChild;
return(title+ "was removed");
}
else{
String minTitle = minTitle(root);
root.title = minTitle;
remove(root.leftChild,minTitle);
return(title+ "was removed");
}
}
else if(title.compareTo(root.title)<0){
remove(root.leftChild, title);
}
else{
remove(root.rightChild, title);
}
}

public void remove (String key, BSTNode pos)
{
if (pos == null) return;
if (key.compareTo(pos.key)<0)
remove (key, pos.leftChild);
else if (key.compareTo(pos.key)>0)
remove (key, pos.rightChild);
else {
if (pos.leftChild != null && pos.rightChild != null)
{
/* pos has two children */
BSTNode maxFromLeft = findMax (pos.leftChild); //need to make a findMax helper
//"Replacing " pos.key " with " maxFromLeft.key
pos.key = maxFromLeft.key;
remove (maxFromLeft.key, pos.leftChild);
}
else if(pos.leftChild != null) {
/* node pointed by pos has at most one child */
BSTNode trash = pos;
//"Promoting " pos.leftChild.key " to replace " pos.key
pos = pos.leftChild;
trash = null;
}
else if(pos.rightChild != null) {
/* node pointed by pos has at most one child */
BSTNode trash = pos;
/* "Promoting " pos.rightChild.key" to replace " pos.key */
pos = pos.rightChild;
trash = null;
}
else {
pos = null;
}
}
}
This is the remove for an unbalanced tree. I had the code in C++ so I have quickly translated. There may be some minor mistakes though. Does the tree you are coding have to be balanced? I also have the balanced remove if need be. I wasn't quite sure based on the wording of your question. Also make sure you add a private helper function for findMax()

void deleteTreeNode(int data){
root = deleteTreeNode(root ,data);
}
private TreeNode deleteTreeNode(TreeNode root, int data) {
TreeNode cur = root;
if(cur == null){
return cur;
}
if(cur.data > data){
cur.left = deleteTreeNode(cur.left, data);
}else if(cur.data < data){
cur.right = deleteTreeNode(cur.right, data);
}else{
if(cur.left == null && cur.right == null){
cur = null;
}else if(cur.right == null){
cur = cur.left;
}else if(cur.left == null){
cur = cur.right;
}else{
TreeNode temp = findMinFromRight(cur.right);
cur.data = temp.data;
cur.right = deleteTreeNode(cur.right, temp.data);
}
}
return cur;
}
private TreeNode findMinFromRight(TreeNode node) {
while(node.left != null){
node = node.left;
}
return node;
}

To compare objects in java use .equals() method instead of "==" operator
if(title==root.title)
^______see here
you need to use like this
if(title.equals(root.title))
or if you are interesed to ignore the case follow below code
if(title.equalsIgnoreCase(root.title))

private void deleteNode(Node temp, int n) {
if (temp == null)
return;
if (temp.number == n) {
if (temp.left == null || temp.right == null) {
Node current = temp.left == null ? temp.right : temp.left;
if (getParent(temp.number, root).left == temp)
getParent(temp.number, root).left = current;
else
getParent(temp.number, root).right = current;
} else {
Node successor = findMax(temp.left);
int data = successor.number;
deleteNode(temp.left, data);
temp.number = data;
}
} else if (temp.number > n) {
deleteNode(temp.left, n);
} else {
deleteNode(temp.right, n);
}
}

I know this is a very old question but anyways... The accepted answer's implementation is taken from c++, so the idea of pointers still exists which should be changed as there are no pointers in Java. So every time when you change the node to null or something else, that instance of the node is changed but not the original one This implementation is taken from one of the coursera course on algorithms.
public TreeNode deleteBSTNode(int value,TreeNode node)
{
if(node==null)
{
System.out.println("the value " + value + " is not found");
return null;
}
//delete
if(node.data>value) node.left = deleteBSTNode(value,node.left);
else if(node.data<value) node.right = deleteBSTNode(value,node.right);
else{
if(node.isLeaf())
return null;
if(node.right==null)
return node.left;
if(node.left==null)
return node.right;
TreeNode successor = findMax(node.left);
int data = successor.data;
deleteBSTNode(data, node.left);
node.data = data;
}
return node;
}
All the links between the nodes are pertained using the return value from the recursion.

For the Depth First Post-Order traversal and removal, use:
/*
*
* Remove uses
* depth-first Post-order traversal.
*
* The Depth First Post-order traversal follows:
* Left_Child -> Right-Child -> Node convention
*
* Partial Logic was implemented from this source:
* https://stackoverflow.com/questions/19870680/remove-method-binary-search-tree
* by: sanjay
*/
#SuppressWarnings("unchecked")
public BinarySearchTreeVertex<E> remove(BinarySearchTreeVertex<E> rootParameter, E eParameter) {
BinarySearchTreeVertex<E> deleteNode = rootParameter;
if ( deleteNode == null ) {
return deleteNode; }
if ( deleteNode.compareTo(eParameter) == 1 ) {
deleteNode.left_child = remove(deleteNode.left_child, eParameter); }
else if ( deleteNode.compareTo(eParameter) == -1 ) {
deleteNode.right_child = remove(deleteNode.right_child, eParameter); }
else {
if ( deleteNode.left_child == null && deleteNode.right_child == null ) {
deleteNode = null;
}
else if ( deleteNode.right_child == null ) {
deleteNode = deleteNode.left_child; }
else if ( deleteNode.left_child == null ) {
deleteNode = deleteNode.right_child; }
else {
BinarySearchTreeVertex<E> interNode = findMaxLeftBranch( deleteNode.left_child );
deleteNode.e = interNode.e;
deleteNode.left_child = remove(deleteNode.left_child, interNode.e);
}
} return deleteNode; } // End of remove(E e)
/*
* Checking right branch for the swap value
*/
#SuppressWarnings("rawtypes")
public BinarySearchTreeVertex findMaxLeftBranch( BinarySearchTreeVertex vertexParameter ) {
while (vertexParameter.right_child != null ) {
vertexParameter = vertexParameter.right_child; }
return vertexParameter; } // End of findMinRightBranch

Related

Binary Search Tree - print out number of leaves

I have a program that is a binary search tree, the method searches for a specific word. I'm having two problems.
First is I would like to print the true or false from this method (basically making a system.out that says if the word was found), I'm assuming I would do it in main but I'm not sure how to do that.
The second problem is that I also need to print out how many leaves are in the tree, I was going to use a counter of some sort in the method but I didn't work.
My method is below but I also included it inside the class to help clear up any confusion.
Any help would be greatly appreciated.
public boolean check(BSTNode t,String key)
{
if (t == null) return false;
if (t.word.equals(key)) return true;
if (check(t.left,key)) return true;
if (check(t.right,key)) return true;
return false;
}
Whole class:
public class BST
{
BSTNode root;
BST() {
root = null;
}
public void add2Tree(String st)
{
BSTNode newNode = new BSTNode(st);
if (this.root == null) {
root = newNode;
} else {
root = addInOrder(root, newNode);
}
}
// private BSTNode insert2(BSTNode root, BSTNode newNode)
// {
// if (root == null)
// root = newNode;
// else {
// System.out.println(root.word + " " + newNode.word);
// if (root.word.compareTo(newNode.word) > 0)
// {
// root.left = (insert2(root.lTree, newNode));
// System.out.println(" left ");
// } else
// {
// root.rTree = (insert2(root.rTree, newNode));
// System.out.println(" right ");
// }
// }
// return root;
// }
public BSTNode addInOrder(BSTNode focus, BSTNode newNode) {
int comparevalue = 0;
if (focus == null) {
focus = newNode;
}
if (focus != null) {
comparevalue = newNode.word.compareTo(focus.word);
}
if (comparevalue < 0) {
focus.left = addInOrder(focus.left, newNode);
} else if (comparevalue > 0) {
focus.right = addInOrder(focus.right, newNode);
}
return (focus);
}
public void ioprint() {
System.out.println(" start inorder");
if (root == null)
System.out.println(" Null");
printinorder(root);
}
public void printinorder(BSTNode t) {
if (t != null) {
printinorder(t.left);
System.out.println(t.word);
printinorder(t.right);
}
}
public boolean check(BSTNode t,String key)
{
if (t == null) return false;
if (t.word.equals(key)) return true;
if (check(t.left,key)) return true;
if (check(t.right,key)) return true;
return false;
}
public BSTNode getroot(){
return root;
}
}
How to print true/false:
Create another class, call it Solution, Test or whatever you like.
Add a main method to it.
Populate your BST.
Call System.out.println(check(bstRoot, key)).
You can check this link to find out how to count the number of nodes in BST, it's pretty straightforward:
Counting the nodes in a binary search tree
private int countNodes(BSTNode current) {
// if it's null, it doesn't exist, return 0
if (current == null) return 0;
// count myself + my left child + my right child
return 1 + nodes(current.left) + nodes(current.right);
}

Remove a leaf from a BinaryTree

My code below will remove a tree with two children, or one child. But a leaf (a tree with zero children) I can't seem to crack. My BSTNode<E> also contains a .parent which identifies it's parent. I'm not sure if that would help with this implementation or not.
#Override
public E delete(E target) {
return delete(this.root, target);
}
private E delete(BSTNode<E> localRoot, E target) {
// ... Trying to delete an item that's not in the tree?
if (localRoot == null) {
return null;
}
int compareResult = c.compare(target, localRoot.data);
// Traverse the tree...
if (compareResult < 0) {
return delete(localRoot.left, target);
} else if (compareResult > 0) {
return delete(localRoot.right, target);
} else {
// Found the item! Oh boy here we go!
E retVal = localRoot.data;
/*
* Both left and right exist under the targeted node.
* Find the largest child under the right side of the node.
* Set the largest data to the 'deleted' node, then delete that node.
*/
if (localRoot.left != null && localRoot.right != null) {
/*
* Two children, find the smallest and assign it.
*/
localRoot.data = localRoot.right.data;
localRoot.right = findLargestChild(localRoot.right);
} else if (localRoot.left != null) {
localRoot.data = localRoot.left.data;
localRoot.left = findSmallestChild(localRoot.left);
} else if (localRoot.right != null) {
localRoot.data = localRoot.right.data;
localRoot.right = findLargestChild(localRoot.right);
} else {
/*
* TODO:
* Remove a leaf.
*/
System.out.println("Removing leaf..." + localRoot.data.toString());
localRoot = null;
}
return retVal;
}
}
Using localRoot.parent I was able to delete (null) the child of the localRoot's parent. This feels backwards, but it's passing JUnit Tests...
private E delete(BSTNode<E> localRoot, E target) {
// ... Trying to delete an item that's not in the tree?
if (localRoot == null) {
return null;
}
int compareResult = c.compare(target, localRoot.data);
// Traverse the tree...
if (compareResult < 0) {
return delete(localRoot.left, target);
} else if (compareResult > 0) {
return delete(localRoot.right, target);
} else {
// Found the item! Oh boy here we go!
E retVal = localRoot.data;
if (localRoot.right != null) {
/*
* Assign the largest value to the tree.
*/
localRoot.data = localRoot.right.data;
localRoot.right = findLargestChild(localRoot.right);
} else if (localRoot.left != null) {
/*
* Since the largest value didn't exist, assign the smallest.
*/
localRoot.data = localRoot.left.data;
localRoot.left = findSmallestChild(localRoot.left);
} else {
/*
* Remove a leaf.
*/
System.out.println("Removing leaf or left..." + localRoot.data.toString());
if (c.compare(target, localRoot.parent.left.data) == 0) {
localRoot.parent.left = null;
} else {
localRoot.parent.right = null;
}
}
return retVal;
}
}

Null Pointer while Traversing through Binary Tree

I was doing an assignment in which I'm supposed to create a binary tree and define given functions from its abstract superclass (AbstractBinaryTree.java).
While working on a function called getNumbers() which is basically going to traverse through the whole tree whilst adding values from each node to an array list which it returns. There seems to be a null pointer in one of my if statements.
AbstractBinaryTree.java
import java.util.ArrayList;
public abstract class AbstractBinaryTree
{
protected Node root;
protected int sizeOfTree;
public AbstractBinaryTree()
{
root = null;
sizeOfTree = 0;
}
public int size(){ return sizeOfTree; }
/** compute the depth of a node */
public abstract int depth(Node node);
/** Check if a number is in the tree or not */
public abstract boolean find(Integer i);
/** Create a list of all the numbers in the tree. */
/* If a number appears N times in the tree then this */
/* number should appear N times in the returned list */
public abstract ArrayList<Integer> getNumbers();
/** Adds a leaf to the tree with number specifed by input. */
public abstract void addLeaf(Integer i);
/** Removes "some" leaf from the tree. */
/* If the tree is empty should return null */
public abstract Node removeLeaf();
// these methods are only needed if you wish
// use the TreeGUI visualization program
public int getheight(Node n){
if( n == null) return 0;
return 1 + Math.max(
getheight(n.getLeft()) , getheight(n.getRight())
);
}
public int height(){ return getheight(root); }
}
Node.java File.
public class Node{
protected Integer data;
protected Node left;
protected Node right;
public Node(Integer data)
{
this.data = data;
this.left = this.right = null;
}
public Node(Integer data, Node left, Node right){
this.data = data;
this.left = left;
this.right = right;
}
public Integer getData(){ return this.data; }
public Node getLeft(){ return this.left; }
public Node getRight(){ return this.right; }
public void setLeft(Node left){ this.left = left; }
public void setRight(Node right){ this.right = right; }
public void setData(Integer data){ this.data = data; }
}
BinaryTree.java
import java.util.ArrayList;
import java.util.*;
// Student Name: Adrian Robertson
// Student Number: 101020295
//
// References: Collier, R. "Lectures Notes for COMP1406C- Introduction to Computer Science II" [PDF documents]. Retrieved from cuLearn: https://www.carleton.ca/culearn/(Winter2016).//
// References: http://codereview.stackexchange.com/questions/13255/deleting-a-node-from-a-binary-search-tree
// http://www.algolist.net/Data_structures/Binary_search_tree/Removal
// http://www.geeksforgeeks.org/inorder-tree-traversal- without-recursion-and-without-stack/
public class BinaryTree extends AbstractBinaryTree
{
protected Node root = new Node(12);
public static BinaryTree create()
{
BinaryTree tempTree = new BinaryTree();
//creating all the nodes
Node temp10 = new Node(10);
Node temp40 = new Node(40);
Node temp30 = new Node(30);
Node temp29 = new Node(29);
Node temp51 = new Node(51);
Node temp61 = new Node(61);
Node temp72 = new Node(72);
Node temp31 = new Node(31);
Node temp32 = new Node(32);
Node temp42 = new Node(42);
Node temp34 = new Node(34);
Node temp2 = new Node(2);
Node temp61x2 = new Node(61);
Node temp66 = new Node(66);
Node temp3 = new Node(3);
Node temp73 = new Node(73);
Node temp74 = new Node(74);
Node temp5 = new Node(5);
//setting up the tree
if (tempTree.root.getData() == null)
{
tempTree.root.setData(12);
tempTree.root.setLeft(temp10);
tempTree.root.setRight(temp40);
}
temp10.setLeft(temp30);
temp30.setRight(temp29);
temp29.setRight(temp51);
temp51.setLeft(temp61);
temp51.setRight(temp72);
temp40.setLeft(temp31);
temp31.setLeft(temp42);
temp31.setRight(temp34);
temp34.setLeft(temp61x2);
temp61x2.setLeft(temp66);
temp61x2.setRight(temp73);
temp40.setRight(temp32);
temp32.setRight(temp2);
temp2.setLeft(temp3);
temp3.setRight(temp74);
temp74.setLeft(temp5);
return tempTree;
}
public int depth(Node node)
{
Node current = this.root;
int counter = 1;
while(node != current)
{
if (node.getData() > current.getData())
current = current.getRight();
if (node.getData() < current.getData())
current = current.getLeft();
}
return counter;
}
public boolean find(Integer i)
{
boolean found = false;
Node current = this.root;
if (i == current.getData())
found = true;
while (i != current.getData())
{
if (i > current.getData())
current = current.getRight();
if (i < current.getData())
current = current.getLeft();
if (i == current.getData())
found = true;
}
return found;
}
public ArrayList<Integer> getNumbers()
{
ArrayList<Integer> temp = new ArrayList<Integer>();
Node current = this.root;
Node Pre = new Node(null);
while (current.getData() != null )
{
if (current.getLeft().getData() == null)
{
temp.add(current.getData());
current = current.getRight();
}
else
{
/* Find the inorder predecessor of current */
Pre = current.getLeft();
while(Pre.getRight() != null && Pre.getRight() != current)
Pre = Pre.getRight();
/* Make current as right child of its inorder predecessor */
if (Pre.getRight() == null)
{
Pre.setRight(current);
current = current.getLeft();
}
/* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecssor */
else
{
Pre.setRight(null);
temp.add(current.getData());
current = current.getRight();
}/* End of if condition Pre.right == NULL */
}/* End of if condition current.left == NULL*/
}/*End of while */
Collections.sort(temp);
return temp;
}
public void addLeaf(Integer i)
{
insert(this.root, i);
}
public static void insert(Node node, int value) //insert a node Based on provided argument where node is the root of tree
{
if (node == null)
{
Node first = new Node(value);
node = first;
}
else if (value < node.getData())
{
if (node.left != null)
{
insert(node.left, value);
}
else
{
System.out.println(" > Inserted " + value + " to left of node " + node.getData());
Node newNode = new Node(value);
node.left = newNode;
}
}
else if (value > node.getData())
{
if (node.right != null)
{
insert(node.right, value);
}
else
{
System.out.println(" > Inserted " + value + " to right of node " + node.getData());
Node newNode = new Node(value);
node.right = newNode;
}
}
}
public Node removeLeaf()
{
Node tempA = new Node(61); //create a new node with that value
deleteNodeBST(this.root, 61); //delete the node containing that leaf value
return tempA; //return the copy of that node
}
//delete given node with given value
public boolean deleteNodeBST(Node node, int data) {
ArrayList<Integer> temp = this.getNumbers();
if (node == null) {
return false;
}
if (node.getData() == data) {
if ((node.getLeft() == null) && (node.getRight() == null)) {
// leaf node
node = null;
return true;
}
if ((node.getLeft() != null) && (node.getRight() != null)) {
// node with two children
node.setData(temp.get(0));
return true;
}
// either left child or right child
if (node.getLeft() != null) {
this.root.setLeft(node.getLeft());
node = null;
return true;
}
if (node.getRight() != null) {
this.root.setRight(node.getRight());
node = null;
return true;
}
}
this.root = node;
if (node.getData() > data) {
return deleteNodeBST(node.getLeft(), data);
} else {
return deleteNodeBST(node.getRight(), data);
}
}
public static void main(String args[])
{
BinaryTree myTree = new BinaryTree();
myTree.create();
System.out.println(myTree.getNumbers());
}
}
The create function creates a binary tree and returns that binary tree. This is the predefined binary tree that I was supposed to create according to assignment guidelines. I understand that the tree values are not organised properly as they would be in a proper binary tree. Is that was causes the null pointer during traversal? Cause the traversal is taylored to work for a proper Binary tree.
In class BinaryTree, you initialize the left and right of your root node only if the haven't data. But the root node is create with data...
You should invert the condition in :
//setting up the tree
if (tempTree.root.getData() == null)
And add a test in getNumbers() :
if (current.getLeft() == null || current.getLeft().getData() == null)
In the BinaryTree class, getNumbers() method and while loop. Maybe your problem is here:
if (current.getLeft().getData() == null) {
temp.add(current.getData());
current = current.getRight();
}
When you call current.getLeft(), it will return null when the left Node is null. And then, you call getData() it will throw a NullPointerException. If you're not sure that it always not null check it before you call any methods of it. Example you can change the if statement to:
if (current.getLeft() != null && current.getLeft().getData() == null) {
temp.add(current.getData());
current = current.getRight();
}
Or:
Node left = current.getLeft();
if (left == null) {
//TODO something here
} else if (left.getData() == null) {
temp.add(current.getData());
current = current.getRight();
}
Please update your getNumbers - method accordingly,
You need to put right checks before work with reference type.
public ArrayList<Integer> getNumbers()
{
ArrayList<Integer> temp = new ArrayList<Integer>();
Node current = this.root;
Node Pre = new Node(null);
while (current != null && current.getData() != null ) // Fix here... Add : current != null
{
if (current.getLeft() != null && current.getLeft().getData() == null) // Fix here... Add : current.getLeft() != null
{
temp.add(current.getData());
current = current.getRight();
}
else
{
/* Find the inorder predecessor of current */
Pre = current.getLeft();
while(Pre != null && Pre.getRight() != null && Pre.getRight() != current) // Fix here... Add : Pre != null
Pre = Pre.getRight();
/* Make current as right child of its inorder predecessor */
if (Pre != null && Pre.getRight() == null) // Fix here... Add : Pre != null
{
Pre.setRight(current);
current = current.getLeft();
}
/* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecssor */
else
{
if(Pre != null){ // Fix here... Add : Pre != null
Pre.setRight(null);
}
temp.add(current.getData());
current = current.getRight();
}/* End of if condition Pre.right == NULL */
}/* End of if condition current.left == NULL*/
}/*End of while */
Collections.sort(temp);
return temp;
}

Java pass by value with recursion

The following is a simple implementation of Binary search tree using java. However, the code always outputs "BST empty!!" despite inserting elements. Where am I going wrong? I suspect I'm going wrong with recursion. Any help is greatly appreciated.
public class BinarySearchTree {
NODE root;
BinarySearchTree(){
root = null;
}
void insert(NODE nodeptr,int key){
if(root == null){
nodeptr = new NODE(key);
return;
}
if(nodeptr == null){
nodeptr = new NODE(key);
return;
}
if(key <= nodeptr.data){
insert(nodeptr.left,key);
}
else{
insert(nodeptr.right,key);
}
}
void inorder(NODE nodeptr){
if(nodeptr == null){
System.out.println("BST empty!!");
return;
}
inorder(nodeptr.left);
System.out.println(nodeptr.data + " ");
inorder(nodeptr.right);
}
/*driver program*/
public static void main(String args[]){
int[] a = {20,30,40,24,39};
BinarySearchTree bst = new BinarySearchTree();
for (int i: a){
bst.insert(bst.root,i);
}
bst.inorder(bst.root);
}
}
class NODE{
int data;
NODE left,right;
NODE(int data){
this.data = data;
left = null;
right = null;
}
}
Your insert method never assigns value to the root, so it remains null.
If I understand your code, your insert should look like this :
void insert(NODE nodeptr,int key){
if(root == null){
root = new NODE(key);
return;
}
if(nodeptr == null){
insert (root, key);
return;
}
if(key <= nodeptr.data){
if (nodeptr.left != null)
insert(nodeptr.left,key);
else
nodeptr.left = new NODE(key);
}
else{
if (nodeptr.right != null)
insert(nodeptr.right,key);
else
nodeptr.right = new NODE(key);
}
}
If the root is null, ignore the passed nodeptr and put key at the root of the tree.
If nodeptr is null, try to insert the new key starting at the root of the tree.
otherwise, once you find a null nodeptr.left or nodeptr.right, you must put the new key there, because if you make another recursive call, you would be passing a null Node to it, and the recursion would never end.
Expanding from Erans answer you could change it to:
public void insert(int key){
if(root == null){
root = new NODE(key);
return;
}
insert(root,key)
}
private void insert(NODE nodeptr,int key){
if(key <= nodeptr.data){
if(nodeptr.left == null){
nodeptr.left = new NODE(key)
}
else {
insert(nodeptr.left,key);
}
}
else{
if(nodeptr.right == null){
nodeptr.right = new NODE(key)
}
else {
insert(nodeptr.right,key);
}
}
}
Edit: As he has added his own code now its just a matter of what style you like better. A single method or two methods from which the public one has only one parameter.
I wanted my insert method something like this. Got it to working finally. Thank you all for your precious time.
NODE insert(NODE nodeptr,int key){
if(nodeptr == null){
nodeptr = new NODE(key);
}
else if(key <= nodeptr.data){
nodeptr.left = insert(nodeptr.left,key);
}
else{
nodeptr.right = insert(nodeptr.right,key);
}
return nodeptr;
}
I would call insert method from main something like this:
bst.root = bst.insert(bst.root,i);

java binary tree insert function non recursive

I have written a code for inserting to the binary tree an element generic's type which is ordered by their names. Don't think it is correct though.
public boolean insert(E e) {
BTNode temp = root;
if (root == null) {
root.setElement(e);
}
while (temp != null)
if (temp.element().getClass().getName().compareTo(e.getClass().getName()) < 0) {
temp = temp.getRight();
} else {
temp = temp.getLeft();
}
temp.setElement(e);
return true;
}
Can you suggest me corrections ?
An insert would need to create a new node. I don't now how to create them as I haven't see the constuctor, but I suggest something along the lines of:
public boolean insert(E e) {
if (root == null) {
root = new BTNode();
root.setElement(e); //how would this work with a null root?
return true; //that's it, we're done (when is this ever false by the way?)
}
BTNode current = root;
while (true) { //brackets! indenting is important for readabilty
BTNode parent=current;
if (current.element().getClass().getName().compareTo(e.getClass().getName()) < 0) {
current = current.getRight();
if(current==null) { //we don't have a right node, need to make one
current = new BTNode();
parent.setRight(current);
break; //we have a new node in "current" that is empty
}
} else {
current= current.getLeft();
if(current==null) { //we don't have a left node, need to make one
current = new BTNode();
parent.setLeft(current);
break; //we have a new node in "current" that is empty
}
}
}
current.setElement(e);
return true;
}
public Boolean add(int data){
Node node = new Node(data);
if(isEmpty()){
root = node;
}else{
Node temp = root;
while(true){
if(data < temp.getData()){
if(temp.getLeft() != null)
temp = temp.getLeft();
else
break;
}else{
if(temp.getRight() != null)
temp = temp.getRight();
else
break;
}
}
if(data < temp.getData())
temp.setLeft(node);
else
temp.setRight(node);
}
return true;
}
As amadeus mentioned, the while loop should not have a semicolon at the end :
BTNode temp = root;
if (root == null) {
root.setElement(e);
return;
}
while (temp != null)
{
if (temp.element().getClass().getName().compareTo(e.getClass().getName()) < 0) {
if(temp.getRight() != null)
temp = temp.getRight();
else
{
temp.createRight(e);
temp = null; //or break
}
} else {
if(temp.getLeft() != null)
temp = temp.getLeft();
else
{
temp.createLeft(e);
temp = null; //or break
}
}
}
return true;

Categories

Resources