Removing a node from Binary Search Tree (BTS), and successor method - java

In my new class assignment, one of the classes in my program I have to write is a BinarySearchTree class. There are 2 methods on which I am struggling a bit, and that's the remove method and successor method.
The binary search tree only stores data in the internal nodes, so the leaf nodes are empty, but not null. however in my remove method I always get an nullPointerException at if(parent.getLeft() == nodeToBeRemoved) and I am not sure why.
Here is my code for remove method:
public void remove(Pair k) throws DictionaryException {
BinaryNode nodeToBeRemoved = searchTreeNode(root, k); //Searches the tree for the node to be removed.
if(nodeToBeRemoved.isLeaf()) { //If the search returns a leaf node, the node to be removed is not in the tree.
throw new DictionaryException("key");
} else {
//If the node to be removed has one child (plus one leaf child) or both children are leaf nodes.
if(nodeToBeRemoved.getLeft().isLeaf() || nodeToBeRemoved.getRight().isLeaf()) {
BinaryNode childNode;
if(nodeToBeRemoved.getLeft().isLeaf()) {
childNode = nodeToBeRemoved.getRight();
} else {
childNode = nodeToBeRemoved.getLeft();
}
BinaryNode parent = nodeToBeRemoved.getParent(); //Parent of the node to be removed.
if(nodeToBeRemoved == root) { //If the node to be removed is the root, the child is set to be the new root.
root = childNode;
} else {
if(parent.getLeft() == nodeToBeRemoved) {
parent.setLeft(childNode);
} else {
parent.setRight(childNode);
}
}
} else { //If the node to be removed has two children (non leaf children).
BinaryNode successorNode = smallestNode(nodeToBeRemoved.getRight()); //Finds the successor node of the node to be removed.
nodeToBeRemoved.setData(successorNode.getData()); //Sets the node to be removed data to be the successor node's data.
remove(successorNode.getData().getKey()); //The successor is then removed.
}
}
}
and my put method, in case it's actually something wrong with that:
public void put(Record r) throws DictionaryException {
BinaryNode newNode = searchTreeNode(root, r.getKey()); //Searches the tree for the node.
if(!newNode.isLeaf()) { //If the node is not a leaf, then the data is already in the tree, so exception is thrown.
throw new DictionaryException("key");
} else { //Otherwise, the data item is not in the tree, and will be added.
newNode.setData(r);
newNode.setLeft(new BinaryNode()); //Sets the left child to be a leaf node.
newNode.setRight(new BinaryNode()); //Sets the right child to be a leaf node.
}
}
The successor method takes in key "k" and returns the data stored in the successor node, however the key "k" does not have to be stored in any of the node in the tree already, so what I did was temporarily added it to the tree, found the successor node and then removed it using the remove method. However, using the test.java file I received from the prof, this method fails the test. Here is my successor code:
public Record successor(Pair k) {
boolean added = false; //A boolean variable to determine if the key is added to the tree.
BinaryNode tempNode = root;
//If the key is not in any of the nodes in the tree, then add this node to the tree.
if(searchTreeNode(tempNode, k).isLeaf()) {
put(new Record(k, null));
added = true; //sets added to true, showing that the node with "key" was added.
}
BinaryNode inputNode = searchTreeNode(tempNode, k);
//If the right child of the node is not null, then the successor is the smallest node in the right subtree.
if(!inputNode.getRight().isLeaf()) {
return smallestNode(inputNode.getRight()).getData();
}
//Otherwise, we have to search up the tree until the parent of the node is the left child of another node. then
//That "another node" will be the first right ancestor, which is the successor node.
BinaryNode inputNodeParent = inputNode.getParent();
while(inputNodeParent != null && inputNode == inputNodeParent.getRight()) {
inputNode = inputNodeParent;
inputNodeParent = inputNodeParent.getParent();
}
Record dataValue = inputNodeParent.getData();
//If the key is added to the tree, we need to remove it now, since it was not originally in the tree.
if(added == true) {
remove(k);
added = false;
}
return dataValue;
}
And the searchTreeNode method used in put and remove:
private BinaryNode searchTreeNode(BinaryNode r, Pair k) {
BinaryNode tempNode = r; //duplicates the root node.
BinaryNode prev = r.getParent();
if(tempNode.isLeaf()) {
return tempNode;
} else {
if(tempNode.getData().getKey().compareTo(k) == 0) {
return tempNode;
} else if(tempNode.getData().getKey().compareTo(k) == 1) {
return searchTreeNode(tempNode.getLeft(), k);
} else {
return searchTreeNode(tempNode.getRight(), k);
}
}
}
I don't really know why I get the nullPointerException error in the remove method and not really sure why successor method fails either.
Edit
Code for BinaryNode getParent method along with the constructor:
public BinaryNode(Record value, BinaryNode left, BinaryNode right, BinaryNode parent) {
recordValue = value; //Initializes the Record object.
leftNode = left; //Initializes the left child of this node.
rightNode = right; //Initializes the right child of this node.
parentNode = parent; //Initializes the parent of this node.
}
public BinaryNode() {
//Initializes all the variable to null.
recordValue = null;
leftNode = null;
rightNode = null;
parentNode = null;
}
public BinaryNode getParent() {
return parentNode;
}

Related

Java: Binary Search Tree

I decided to create a Binary Search Tree using java, and what I want to do is delete the Max element from the tree, so I created this part of code:
public Node<T> removeMax(Node<T> node) {
if (node == null)
return null;
if (node.right == null) {
Node<T> n = node;
node = null;
return n;
}
return removeMax(node.right);
}
The method returns the Max element, but it doesn't remove it from the tree. As you can see, I tried to remove it in this part:
Node<T> n = node;
node = null;
return n;
But, when I print the elements in the tree, it shows the "removed" ones too.
What am I doing wrong?
EDIT: What I'm really trying to do is delete the Max node and return it so I can now which one was deleted.
Now I noticed you wanted to know which node gets deleted. All you can do is to delete the maximum node and print the tree:
public void deleteMax(Node<T> root) {
Node<T> current = root;
while (current.right.right != null) {
current = current.right;
}
if(current.right.left!=null) {//max has 1 child to left
current.right=current.right.left;
}
else {//max has no child
current.right=null;
}
}
public String printInfix(Node<T> root) {//prints all the data in the tree in infix order
if(root==null) {
return "";
}
return printAll(root.left+" "+root.data+" "+printAll(root.right);
}
You want to delete a node in a binary search tree. So, basically what you want to do is to make it inaccessible. To do that, you have to nullify the reference to it, i.e, make its parent's corresponding pointer to it as null.
Change this:
if (node.right == null) {
Node<T> n = node;
node = null;
return n;
}
To this:
if (node.right.right == null) {
Node<T> n = node.right;
node.right = node.right.left;
return n;
}
Also you need to take care of the case when the root is the maximum element of the tree. So, if you have some reference to the root of BST, add this case before the above case:
if (node.right == null) {
Node<T> n = node;
referenceToTheRootOfBST = node.left;
return n;
}
If you don't have a reference to the root of the BST, what you can do is deep copy the left node of the root and then remove the left node. So, the above case changes to:
if (node.right == null) {
Node<T> n = node;
//I'll assume you don't call this function if root is the only element.
//if root is the only element.If that's the case, then just make the
//root null before calling this function.
Node<T> leftNode = node.left;
node.value = leftNode.value;
node.left = leftNode.left;
node.right = leftNode.right;
return n;
}
Another simple way to handle the case that root is the maximum element is to check it before actually calling this function. Simply check if root has a right node, and if it doesn't have it, reallocate the root reference.

What changes when implementing lazy deletion into a binary search tree exactly?

Okay so I've been looking into this for days and everytime I think I've gotten it down I start writing code and I get to a point where I just can't figure out what exactly to do.
The tree isn't recursive, so I can follow everything really until I start trying to modify it so it uses lazy deletion instead of real deletion. (Right now it nulls out the node it deletes)
What I have managed to figure out:
I added a flag to the node class to set them as deleted
I've implemented a search method that works, it even seems to register if my nodes are deleted or not(lazily)
I know that the rest of the tree class should treat the nodes that are flagged as deleted such that they are not there.
What I don't know:
I've looked at MANY resources and some say all you need to do is set
the node's deleted flag to true. Does this mean that I don't have to
worry about the linking after their flag is set?
Is an appropriate way to do this very superficial? As in, just don't let the methods report that something is found if the flag is set to deleted even though the methods do find something?
In what method(s) should I change to use lazy deletion? Only the delete() method?
If I only change the delete method, how is this picked up by the other methods?
Does the search method look okay?
Here's the rest of the code so you can see what I'm using. I'm really frustrated because I honestly understand how to delete nodes completely way better then this stupid lazy deletion implementation. It's what they teach in the book! lol
Please help... :(
Search Method
So here's my search method:
public String search(E data){
Node<E> current = root;
String result = "";
while(current != null){
if(data.compareTo(current.e) < 0){
current = current.left;
}
else if (data.compareTo(current.e) > 0){
current = current.right;
}
else{
if (current.isDeleted == false){
return result += "Found node with matching data that is not deleted!";
}
else{
return result += "Found deleted data, not usable, continuing search\n";
}
}
}
return result += "Did not find non-deleted matching node!";
}
Tree Class
Tree Code (The real deletion method is commented out at the end so I could replace it with the lazy deletion):
package mybinarytreeexample;
public class MyBinaryTree> {
private Node<E> root = null;
public class Node<E> {
public boolean isDeleted = false;
public E e = null;
public Node<E> left = null;
public Node<E> right = null;
}
public boolean insert(E e) {
// if empty tree, insert a new node as the root node
// and assign the elementy to it
if (root == null) {
root = new Node();
root.e = e;
return true;
}
// otherwise, binary search until a null child pointer
// is found
Node<E> parent = null;
Node<E> child = root;
while (child != null) {
if (e.compareTo(child.e) < 0) {
parent = child;
child = child.left;
} else if (e.compareTo(child.e) > 0) {
parent = child;
child = child.right;
} else {
if(child.isDeleted){
child.isDeleted = false;
return true;
}
return false;
}
}
// if e < parent.e create a new node, link it to
// the binary tree and assign the element to it
if (e.compareTo(parent.e) < 0) {
parent.left = new Node();
parent.left.e = e;
} else {
parent.right = new Node();
parent.right.e = e;
}
return true;
}
public void inorder() {
System.out.print("inorder: ");
inorder(root);
System.out.println();
}
private void inorder(Node<E> current) {
if (current != null) {
inorder(current.left);
System.out.printf("%3s", current.e);
inorder(current.right);
}
}
public void preorder() {
System.out.print("preorder: ");
preorder(root);
System.out.println();
}
private void preorder(Node<E> current) {
if (current != null) {
System.out.printf("%3s", current.e);
preorder(current.left);
preorder(current.right);
}
}
public void postorder() {
System.out.print("postorder: ");
postorder(root);
System.out.println();
}
private void postorder(Node<E> current) {
if (current != null) {
postorder(current.left);
postorder(current.right);
System.out.printf("%3s", current.e);
}
}
public String search(E data){
Node<E> current = root;
String result = "";
while(current != null){
if(data.compareTo(current.e) < 0){
current = current.left;
}
else if (data.compareTo(current.e) > 0){
current = current.right;
}
else{
if (current.isDeleted == false){
return result += "Found node with matching data that is not deleted!";
}
else{
return result += "Found deleted data, not usable, continuing search\n";
}
}
}
return result += "Did not find non-deleted matching node!";
}
public boolean delete(E e) {
}
// an iterator allows elements to be modified, but can mess with
// the order if element not written with immutable key; it is better
// to use delete to remove and delete/insert to remove or replace a
// node
public java.util.Iterator<E> iterator() {
return new PreorderIterator();
}
private class PreorderIterator implements java.util.Iterator<E> {
private java.util.LinkedList<E> ll = new java.util.LinkedList();
private java.util.Iterator<E> pit= null;
// create a LinkedList object that uses a linked list of nodes that
// contain references to the elements of the nodes of the binary tree
// in preorder
public PreorderIterator() {
buildListInPreorder(root);
pit = ll.iterator();
}
private void buildListInPreorder(Node<E> current) {
if (current != null) {
ll.add(current.e);
buildListInPreorder(current.left);
buildListInPreorder(current.right);
}
}
// check to see if their is another node in the LinkedList
#Override
public boolean hasNext() {
return pit.hasNext();
}
// reference the next node in the LinkedList and return a
// reference to the element in the node of the binary tree
#Override
public E next() {
return pit.next();
}
#Override
public void remove() {
throw new UnsupportedOperationException("NO!");
}
}
}
// binary search until found or not in list
// boolean found = false;
// Node<E> parent = null;
// Node<E> child = root;
//
// while (child != null) {
// if (e.compareTo(child.e) < 0) {
// parent = child;
// child = child.left;
// } else if (e.compareTo(child.e) > 0) {
// parent = child;
// child = child.right;
// } else {
// found = true;
// break;
// }
// }
//
//
// if (found) {
// // if root only is the only node, set root to null
// if (child == root && root.left == null && root.right == null)
// root = null;
// // if leaf, remove
// else if (child.left == null && child.right == null) {
// if (parent.left == child)
// parent.left = null;
// else
// parent.right = null;
// } else
// // if the found node is not a leaf
// // and the found node only has a right child,
// // connect the parent of the found node (the one
// // to be deleted) to the right child of the
// // found node
// if (child.left == null) {
// if (parent.left == child)
// parent.left = child.right;
// else
// parent.right = child.right;
// } else {
// // if the found node has a left child,
// // the node in the left subtree with the largest element
// // (i. e. the right most node in the left subtree)
// // takes the place of the node to be deleted
// Node<E> parentLargest = child;
// Node<E> largest = child.left;
// while (largest.right != null) {
// parentLargest = largest;
// largest = largest.right;
// }
//
// // replace the lement in the found node with the element in
// // the right most node of the left subtree
// child.e = largest.e;
//
// // if the parent of the node of the largest element in the
// // left subtree is the found node, set the left pointer of the
// // found node to point to left child of its left child
// if (parentLargest == child)
// child.left = largest.left;
// else
// // otherwise, set the right child pointer of the parent of
// // largest element in the left subtreeto point to the left
// // subtree of the node of the largest element in the left
// // subtree
// parentLargest.right = largest.left;
// }
//
// } // end if found
//
// return found;
What changes is that your tree only grows in term of real space used, and never shrinks. This can be very useful if you choose a list as a data-structure to implement your tree, rather than the usual construct Node E {V value; E right; E; left}. I will come back on this later.
I've looked at MANY resources and some say all you need to do is set
the node's deleted flag to true. Does this mean that I don't have to
worry about the linking after their flag is set?
Yes, if by linking you mean node.left, node.right. Delete simply mark as deleted and that's it. It change nothing else, and it should not, because x.CompareTo(y) must be still working even if x or y are marked as deleted
Is an appropriate way to do this very superficial? As in, just don't
let the methods report that something is found if the flag is set to
deleted even though the methods do find something?
Well by definition of this method "something" means a node without the deleted flag. Anything with the deleted flag is "nothing" for the user of the tree.
what method(s) should I change to use lazy deletion? Only the delete()
method?
Of course not. You already changed the search method yourself. Let's take the isEmpty(). You should keep a counter of deleted nodes and one of total nodes. If they are equal the tree is empty. Otherwise the tree is not.
There is a small bug in your algorithm. When you insert and find out that you land on a deleted node, you just unmark that node. You must also set the value of the node. After all compareTo doesnt insure all fields are strictly equal, just that the objects are equivalent.
if(child.isDeleted){
child.isDeleted = false;
child.e = e; <---- missing
return true;
}
There might be others.
Side Note:
As said before one instance where this method is useful is a tree backed by an list (let's say array list). With this method the children of element at position i are at position 2*i+1 and 2*i+2. Usually when you delete a node p with children, you replace that node with the leftmost node q of the right subtree (or rightmost node in the left subtree). Here you can just mark p as deleted and swap the value of the deleted node and leftmost. Your array stays intact in memory

Recursive Insert for Binary Tree

I'm working on code for insertion into a binary search tree. It works for the first node I insert, making it the root, but after that it doesn't seem to insert any nodes. I'm sure it's a problem with setting left/right references, but I can't quite figure it out. Please help!
//params: key of node to be inserted, parent node
public void insert(int newKey, TreeNode parent){
//if the root of the tree is empty, insert at root
if(this.getRoot() == null){
this.root = new TreeNode(newKey, null, null);
}
//if the node is null, insert at this node
else if(parent == null)
parent = new TreeNode(newKey, null, null);
else{
//if the value is less than the value of the current node, call insert on the node's left child
if(newKey < parent.getKey()) {
insert(newKey, parent.getLeft());
}
//greater than value of current node, call insert on node's right child
else if(newKey > parent.getKey()){
insert(newKey, parent.getRight());
}
//same as value of current node, increment iteration field by one
else if(newKey == parent.getKey())
parent.incrementIterations();
}
}
My treenodes have key, left, right, and iteration fields, as well as getter/setter functions.
Thank you in advance!
public Node insertNode(Node head, int data) {
if(head == null){
head = new Node();
head.data = data;
return head;
}
if(head.data < data) {
head.right = insertNode(head.right,data);
} else {
head.left = insertNode(head.left, data);
}
return head;
}
If (parent==null) you are creating a node, but you are not associating it to tree back. Its just created and garbage collected.
You should be using insert (newkey, parent) then u still have handle to tree
private AVLNode insert(AVLNode root, int value){
if (root == null) return new AVLNode(value);
if(root.value > value)
root.leftChild = insert(root.rightChild, value);
else
root.rightChild = insert(root.leftChild, value);
return root;
}

BST Only Keeps Last Inserted Value and Makes it Root

I'm trying to populate a binary search tree using an insert(), however when every I 'print' the contents of my BST, I only get the last item that was inserted into the BST. What do I need to fix to make sure all of my value are retaining in the BST?
From debuggin, I think that my problem is that my public void insert() is setting the new value to root evertime it is called. I don't know how to fix it?
Here is my BST CLass:
public class BinarySearchTree<T extends Comparable<T>> {
private class BinarySearchTreeNode<E>{
public BinarySearchTreeNode<E> left, right;
private E data;
private BinarySearchTreeNode (E data) {
this.data = data;
}
}
private BinarySearchTreeNode<T> root;
public boolean isEmpty() {
return root == null;
}
private BinarySearchTreeNode<T> insert(T value, BinarySearchTreeNode<T> ptr) {
if (ptr == null){
ptr = new BinarySearchTreeNode<>(value);
return ptr;
}
int compare = value.compareTo(ptr.data); //when ptr != null, this line and below should execute for each bstStrings.inster(x)
/* pass the value (s1...sN) when compared to (ptr.data) to compare
* when value and ptr.data == 0 re
*/
if (compare == 0) {
return ptr;
}
if (compare < 0) {
while (ptr.left != null){
ptr = ptr.left;
if (ptr.left == null) {//found insertion point
BinarySearchTreeNode<T> node = new BinarySearchTreeNode<>(value);
ptr = ptr.left;
ptr = node;
return ptr;
}
}
}
else {
return insert(value, ptr.left);
}
if (compare > 0) {
if (ptr.right == null) {
BinarySearchTreeNode<T> node = new BinarySearchTreeNode<>(value);
ptr = ptr.right;
ptr = node;
return ptr;
}
}
else {
return insert(value, ptr.right);
}
return ptr;
}
public void insert(T value) {
root = insert(value, root); //****Where I believe the problem is******
}
private void printTree(BinarySearchTreeNode<T>node){
if(node != null){
printTree(node.left);
System.out.println(" " + node.data);
printTree(node.right);
}
}
public void printTree(){
printTree(root);
System.out.println();
}
}
For added context here is my Main() where I am calling the insert() and trying to insert strings into the BST:
public class Main {
public static void main(String[] args) {
BinarySearchTree<String> bstStrings = new BinarySearchTree<String>();
String s = "Hello";
String s1 = "World";
String s2 = "This Morning";
String s3 = "It's";
bstStrings.insert(s);
bstStrings.insert(s1);
bstStrings.insert(s2);
bstStrings.insert(s3); //the only inserted value that is printed below
bstStrings.printTree();
System.out.println();
System.out.println("You should have values above this line!");
}
}
Lastly my console output:
It's
You should have values above this line!
Some hints:
I don't see any recursive calls inside insert. How would you traverse the BST without appropriate recursive calls (into the left or right subtree of the current node based on the value)? I do see some commented out code that looks like it would perform those calls. Why are they commented out?
You're returning the newly inserted node, which you're then setting as root. This will set the root to point to the new node every time. I don't think that's what you want.
If you're trying to handle the special case where the tree is empty, all you need to do is check to see if root is null, then set the new node to that.
There really is no need to return ptr. Since your BST maintains a reference to root, you always have a reference to the root of the tree. Every time you insert, you start with the root and then recursively traverse the tree until you find a suitable place to insert the new node. If you really must return the reference, then you most certainly should not be setting root to that new node!
Here is some pseudocode to help you out:
// Recursive function that inserts a value into a BST
function insert(node, value):
//Handles the case where you have no nodes in the tree, so root is null
if node is null:
node = new Node(value)
// If the value is lesser than the current node's value, we need to insert it
// somewhere in the right subtree
else if value < node.value:
if node.right is null:
// This node doesn't have a right child, so let's insert the new node here
node.right = new Node(value)
else:
// This node has a right child, so let's go further into this subtree to
// find the right place to insert the new node
insert(node.right, value)
// If the value is greater than the current node's value, we need to insert it
// somewhere in the left subtree
else if value > node.value:
if node.left is null:
// This node doesn't have a left child, so let's insert the new node here
node.left = new Node(value)
else:
// This node has a left child, so let's go further into this subtree to
// find the right place to insert the new node
insert(node.left, value)
else:
// A node with this value already exists so let's print out an erro
error("Node with that value already exists")
end function

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