二阶树inorder遍历的非void方法

时间:2011-09-29 05:12:20

标签: java debugging binary-tree nodes

我想知道是否有可能在java中有一个inorder树遍历方法实际上返回一些东西......我试图在给定节点和值的情况下遍历树,返回与值匹配的节点: / p>

/**
 * 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的值并将我的测试混淆为null。

有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:2)

我原本以为你会想要这样的东西:

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