Finding min element of binary search tree - java

I am having trouble finding the smallest element of a binary search tree. I have some code finished, but it is not working.
public T getMinElement(TreeNode<T> node) {
//TODO: implement this
if (node == null){
return null;
}
if (node.getLeftChild() == null){
return (T) node;
}
else{
return getMinElement(node);
}
}

You were almost there! You just need to recurse on the left child of your binary search tree (always guaranteed to be smaller). Also you had some syntax errors, which I fixed.
public <T> T getMinElement(TreeNode<T> node) {
if (node == null){
return null;
}
if (node.getLeftChild() == null){
return node.getData(); // or whatever your method is
} else{
return getMinElement(node.getLeftChild());
}
}

Related

Search method for tree with multiple children per node

I created the following Method to search for a certain ParentReference Id in a Tree that is unsorted and where every node can have any number of children. If the given parentRef matches the Node's parentRef, the Node should be returned.
public static <T>Node<T> search(Node<T> node, int parentRef) {
if(node.getParentRef() == parentRef){
return node;
}
if(node.getChildren()!= null){
for(int i = 0; i < node.getChildren().size(); i++){
if(node.getChildren().get(i).parentRef == parentRef){
return node;
}
else {
search(node.getChildren().get(i), parentRef);
}
}
}
return null;
}
However, it does not work and always returns null but I don't know why. Can anybody explain what I am doing wrong?
In the else branch, you call search recursively, but don't return its value, so it is lost. You should check if it's not null, and if so, return it:
else {
Node<T> result = search(node.getChildren().get(i), parentRef);
if (result != null) {
return result;
}
}

Searching binary tree recursively

Hi I'm having trouble getting this code working correctly. It seems to be jumping out of the stack when it recurses all the way down the leftmost edge of the tree. I just can't seem to figure this one out.
public static Node lookup(Node node, int lookupValue) {
if (node == null) {
return null;
} else {
if (node.value == lookupValue) {
System.out.println("Found");
return node;
} else if(node.left != null) {
return lookup(node.left, lookupValue);
} else if(node.right != null) {
return lookup(node.right, lookupValue);
} else {
return null;
}
}
}
You return whatever is returned form the left sub-tree (if present) without checking the right one. A lot of the else branching isn't necessary when there is a return statement in the if block. Change as follows:
public static Node lookup(Node node, int lookupValue) {
if (node == null)
return null;
if (node.value == lookupValue)
// System.out.println("Found");
return node;
Node rval = lookup(node.left, lookupValue);
// only return if found in left sub-tree
return (rval != null) ? rval : lookup(node.right, lookupValue);
}
Your else if are not correct you chould check the left and right everytimes:
if (node == null) return null;
if (node.value == lookupValue) {
System.out.println("Found");
return node;
}
Node found = lookup(node.left, lookupValue);
if(found != null) {
return found;
}
return lookup(node.right, lookupValue);

Binary Search Tree Recursive Delete

I'm working on Binary Search Trees, and currently working on recursive delete method. I have a bug in my code; it deletes nodes with no children and with one-child. Problem arises when trying to delete node with two children. (Point of reference - I am replacing deleted node with smallest node in Right Subtree)
My code is:
//Driver
public void delete (String val){
root = delete(root, val);
}
//Recursive Delete Method
private static StringNode delete(StringNode node, String v){
StringNode temp;
if(node == null){
return null;
}
if(v.compareTo(node.getString()) < 0){
node.setLeft(delete(node.getLeft(), v));
}
else if(v.compareTo(node.getString()) > 0){
node.setRight(delete(node.getRight(), v));
}
else{
if(node.getLeft() == null){
node = node.getRight();
}
else if(node.getRight() == null){
node = node.getLeft();
}
else{
node = node.getRight();
while(node.getLeft() != null){
node = node.getLeft();
}
node.setRight(delete(node, node.getString()));
}
}
return node;
}
I have debugged and see that I lose a child when re-connecting the nodes after deletion. But I don't know how to correct in my code.
I figured out the bug. I separated the delete method into delete and deleteNode methods. Worked out.

Deleting Value in Binary Tree

I have a slightly working binary search tree delete value function. The only time that it does not work is if you are trying to delete a root that has two children.
public boolean delete(BinaryTreeNode node, int i){
if (node == null){
return false;
} else {
if (node.getKey() == i){
BinaryTreeNode parent = new BinaryTreeNode(0, null, null);
parent.setLeftChild(root);
boolean result = deleteHelper(i, node, parent);
root = parent.getLeftChild();
return result;
} else {
return deleteHelper(i, node, null);
}
}
}
public boolean deleteHelper(int value, BinaryTreeNode curr, BinaryTreeNode parent){
if (value < curr.getKey()){
if (curr.getLeftChild() != null){
return deleteHelper(value, curr.getLeftChild(), curr);
} else {
return false;
}
} else if (value > curr.getKey()){
if (curr.getRightChild() != null){
return deleteHelper(value, curr.getRightChild(), curr);
} else {
return false;
}
} else {
if (curr.getRightChild() != null && curr.getLeftChild() != null){
curr.setKey(findMin(curr.getRightChild()).getKey());
deleteHelper(curr.getKey(), curr.getRightChild(), curr);
} else if (parent.getLeftChild() == curr){
parent.setLeftChild((curr.getLeftChild() != null)?curr.getLeftChild():curr.getRightChild());
} else if (parent.getRightChild() == curr){
parent.setRightChild((curr.getLeftChild() != null)?curr.getLeftChild():curr.getRightChild());
}
return true;
}
}
According to Wikipedia
Deleting a node with two children: Call the node to be deleted N. Do not delete N. Instead, choose either its in-order successor node or its in-order predecessor node, R. Copy the value of R to N, then recursively call delete on R until reaching one of the first two cases.
http://en.wikipedia.org/wiki/Binary_search_tree#Deletion
You can try by successor node as follows:
get successor of node to delete (current)
connect parent of current to successor
connect successor to the left child for current
For more details check out this link
Java, Binary tree remove method

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

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

Categories