遍历树以查找节点

时间:2010-02-13 20:53:24

标签: java algorithm recursion binary-tree

我在树中搜索以查找传递的值。不幸的是,它不起作用。我开始用print打印它,奇怪的是它实际上找到了值,但跳过了return语句。

    /**
  * 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
 }

打印出如下结果:

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)

我不知道这是否有帮助,但这是我的树:

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

感谢您的时间。

4 个答案:

答案 0 :(得分:4)

试试这个:

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
 }

答案 1 :(得分:2)

假设您的树是binary search tree而不是"regular" binary tree

您应该返回递归调用,而不是在方法结束时返回null

这样的事情:

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());
    }
}

答案 2 :(得分:1)

我认为您必须返回searchNodeBeingDeleted(c, node.getLeft())searchNodeBeingDeleted(c, node.getRight())的值,而不仅仅是调用这些方法。

答案 3 :(得分:1)

您正在使用函数中的递归。您看到的'here'是从同一函数创建的函数调用的结果。所以它会向'递归'函数返回一个值,此时你还没有完成,即使你找到了答案,你还是需要继续向上传播。