2016-10-20 116 views
2

我试图搜索非二叉树中的一个节点,而没有实际将节点传递给搜索方法。通过树进行递归搜索而不通过对象

每个节点都有一个name变量。 findChild()方法采用一个名称,并搜索所调用的树来查找具有该名称的节点。

要进行递归搜索,我在子节点上调用findChild(),而不是将子节点传递给findChild()方法。打印语句显示该方法在树中下移,但当堆栈展开时result变量被设置为空,因此该方法始终返回null。我明白为什么这样做,但我不明白如何展开这种类型的递归。任何帮助表示赞赏!

findChild()方法:

public FileNode findChild(String name) { 
    FileNode result = null; 
     for (FileNode child : this.getChildren()) { 
      if (child.getName() == name) { 
       return child; 
      } else { 
       child.findChild(name); 
      } 
     } 
    return result; 
} 
+0

首先,您应该总是使用'.equals'来比较字符串而不是'=='。 '=='将检查相同的对象是否是引用,而'.equals'将检查这些字符串是否相同。 – Erik

回答

0

请问以下的小变化帮助?你的其他条件永远不会分配一个值。

public FileNode findChild(String name) { 
    FileNode result = null; 
     for (FileNode child : this.getChildren()) { 
      if (child.getName() == name) { 
       result = child; 
       break; 
      } else { 
       result = child.findChild(name); 
       if (result != null) 
        break; 
      } 
     } 
    return result; 
} 
1

你在else块扔掉FileNode#findChild结果

试试这个

if (child.getName().equals(name)) { 
    return child; 
} else { 
    FileNode childResult = child.findChild(name); 
    if (childResult != null) { 
     return childResult; 
    } 
}