我想知道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 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);
}
}
现在,我尝试声明一个公共(public)节点来存储该值,但我发现当我运行时这不起作用:
assertEquals(newNode3, BT.contains("3"));
assertEquals(null, BT.contains("abcd"));
returnNode 采用 newNode3 的值并搞乱了我对 null 的测试。
有人能指出我正确的方向吗?
最佳答案
我以为你会想要这样的东西:
/**
* 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;
}
关于java - 二叉树中序遍历的非空方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7592718/