Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary Search Tree implemented in Java - Find Element recursively

Using Java, is it possible to write a recursive method to find an element in a binary search tree? I say no because of the nature of recursive re-tracing back unless I implemented incorrectly? I have been searching the internet and all i can find is an iterative version. Here is my method:

public boolean findValueRecursively(BSTNode node, int value){
   boolean isFound = false;
   BSTNode currentNode = node;

   if (value == currentNode.getData()){
      isFound = true;
      return isFound;
   } else if (value < currentNode.getData()){
      findValueRecursively(currentNode.getLeftNode(), value);
   } else{
      findValueRecursively(currentNode.getRightNode(), value);
   }

  return isFound;
}

// Node data structure
public class BSTNode
{
    private BSTNode leftNode;
    private BSTNode rightNode;
    private int data;
    public BSTNode(int value, BSTNode left, BSTNode right){
       this.leftNode = left;
       this.rightNode = right;
       this.data = value;
    }
}



public static void main(String[] args){
    BST bst = new BST();
    // initialize the root node
    BSTNode bstNode = new BSTNode(4, null, null);
    bst.insert(bstNode, 2);
    bst.insert(bstNode, 5);
    bst.insert(bstNode, 6);
    bst.insert(bstNode, 1);
    bst.insert(bstNode, 3); 
    bst.insert(bstNode, 7);
    if (bst.findValueRecursively(bstNode, 7)){
        System.out.println("element is found! ");
    } else{
        System.out.println("element is not found!");
    }
 }

I get the print as "element is not found".

Any help/tips or suggestions, more than welcome.

Thanks in advance!

like image 524
Allen Avatar asked Apr 20 '26 21:04

Allen


1 Answers

A recursive version:

public boolean findValueRecursively(Node node, int value){
        if(node == null) return false;
        return 
                node.data == value ||
                findValueRecursively(leftNode, value) ||
                findValueRecursively(rightNode, value);
    }
like image 144
Nir Alfasi Avatar answered Apr 23 '26 14:04

Nir Alfasi