Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traversal of a tree to find a node

I am searching through a tree to find a value that is passed. Unfortunately, it does not work. I started debugging it with prints, and what is weird is it actually finds the value, but skips the return statement.

    /**
  * Returns the node with the passed value
  */
 private TreeNode searchNodeBeingDeleted(Comparable c, TreeNode node)
 {  
  if(node == null) 
  {
   return null;
  }

  if(c.equals((Comparable)node.getValue()))
  {
   System.out.println("Here");
   return node;
  }
  else
  {
   if(node.getLeft() != null)
   {
    System.out.println("left");
    searchNodeBeingDeleted(c, node.getLeft());
   }
   if(node.getRight() != null)
   {
    System.out.println("right");
    searchNodeBeingDeleted(c, node.getRight());
   }
  }
  return null; //i think this gives me my null pointer at bottom
 }

It prints out the results as follows:

left
left
right
right
Here
right
left
right
left
right
Exception in thread "main" java.lang.NullPointerException
at Program_14.Driver.main(Driver.java:29)

I dont know if this will help, but here is my tree:

     L
   /   \
  D     R
 / \   / \
A   F M   U
 \       / \
  B     T   V

Thanks for your time.

like image 416
JavaFail Avatar asked Feb 13 '10 20:02

JavaFail


2 Answers

Try this:

private TreeNode searchNodeBeingDeleted(Comparable c, TreeNode node)
 {  
  if(node == null) 
  {
   return null;
  }

  if(c.equals((Comparable)node.getValue()))
  {
   System.out.println("Here");
   return node;
  }
  else
  {
   if(node.getLeft() != null)
   {
    System.out.println("left");
    TreeNode n = searchNodeBeingDeleted(c, node.getLeft());
    if (n != null) {
      return n;
    }
   }
   if(node.getRight() != null)
   {
    System.out.println("right");
    TreeNode n = searchNodeBeingDeleted(c, node.getRight());
    if (n != null) {
      return n;
    }
   }
  }
  return null; //i think this gives me my null pointer at bottom
 }
like image 79
nanda Avatar answered Sep 19 '22 05:09

nanda


Assuming your tree is a binary search tree and not a "regular" binary tree.

You should return your recursive calls and not return null at the end of your method.

Something like this:

private TreeNode searchNodeBeingDeleted(Comparable c, TreeNode node) {
    if(nodle == null) return null;
    int diff = c.compareTo((Comparable)node.getValue());
    if (diff == 0) { // yes, we found a match!
        System.out.println("Here");
        return node;
    }
    else if (diff < 0) { // traverse to the left
        System.out.println("left");
        return searchNodeBeingDeleted(c, node.getLeft());
    }
    else {  // traverse to the right
        System.out.println("right");
        return searchNodeBeingDeleted(c, node.getRight());
    }
}
like image 41
Bart Kiers Avatar answered Sep 18 '22 05:09

Bart Kiers