Java 二叉树有序遍历的非void方法
我想知道在java中是否可能有一个顺序树遍历方法实际返回一些东西。。。我尝试遍历给定节点和值的树,返回与该值匹配的节点:Java 二叉树有序遍历的非void方法,java,debugging,binary-tree,nodes,Java,Debugging,Binary Tree,Nodes,我想知道在java中是否可能有一个顺序树遍历方法实际返回一些东西。。。我尝试遍历给定节点和值的树,返回与该值匹配的节点: /** * Variable for storing found node from inorder search */ private Node returnNode; /** * Perform an inorder search through tree. * If a value is matched, the node is saved to retu
/**
* Variable for storing found node from inorder search
*/
private Node returnNode;
/**
* Perform an inorder search through tree.
* If a value is matched, the node is saved to returnNode, otherwise return null.
* @param node The given node
* @param value The value of the node to be found.
*/
public void inorder(Node node, Object value){
if(node != null){
inorder(node.leftChild, value);
if(node.value.equals(value)){
System.out.println(value + " was found at " + node);
returnNode = node;
}
inorder(node.rightChild, value);
}
}
现在,我已尝试声明一个公共节点来存储该值,但我发现在运行以下命令时,该操作不起作用:
assertEquals(newNode3, BT.contains("3"));
assertEquals(null, BT.contains("abcd"));
其中returnNode接受newNode3的值并将我的空测试搞砸
有人能给我指出正确的方向吗?我原以为你会想要这样的东西:
/**
* Perform an inorder search through tree.
* The first node in order that matches the value is returned, otherwise return null.
* @param node The given node
* @param value The value of the node to be found.
* @return The first node that matches the value, or null
*/
public Node inorder(Node node, Object value){
Node result = null;
if(node != null){
result = inorder(node.leftChild, value);
if( result != null) return result;
if(node.value.equals(value)){
System.out.println(value + " was found at " + node);
return node;
}
result = inorder(node.rightChild, value);
}
return result;
}
好的,我还在喝早茶,但是简单地
返回returnNode不是更容易吗代码>而不是returnNode=node代码>?