树的遍历查找节点 [英] Traversal of a tree to find a node

查看:124
本文介绍了树的遍历查找节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过树搜索找到传递一个值。不幸的是,这是行不通的。我开始与打印调试它,什么是奇怪的是,它实际上找到的价值,但跳过return语句。

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.

推荐答案

试试这个:

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
 }

这篇关于树的遍历查找节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆