【问题标题】:non void method for binary tree inorder traversal二叉树中序遍历的非void方法
【发布时间】:2011-09-29 05:12:20
【问题描述】:

我想知道在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);
    }
}

现在,我尝试声明一个公共节点来存储值,但我发现在运行时这不起作用:

assertEquals(newNode3, BT.contains("3"));
assertEquals(null, BT.contains("abcd"));

returnNode 采用 newNode3 的值并弄乱我的 null 测试。

谁能指出我正确的方向?

【问题讨论】:

  • 好的,我还在喝早茶,但用return returnNode; 代替returnNode = node; 不是更容易吗?

标签: java debugging binary-tree nodes


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-01-12
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 2016-01-09
    • 2021-07-26
    • 1970-01-01
    • 2021-03-08
    相关资源
    最近更新 更多