java - 二叉树中序遍历的非空方法

标签 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 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/

相关文章:

java - 如何根据一列对一维(或二维)数组(多维)进行排序?

java - 在 Java 中恢复使用 mysqldump 创建的备份文件时出错

ios - 存折优惠券无法在safari中打开

java - TreeMap 内存使用

java - 使用 Flying Saucer 从 XHtml 源文本生成 PDF 的代理问题

java - 有没有办法从Flash访问Java库?

c - C Mandelbrot 程序中的二进制错误导致无效操作数

c# - 如何强制 visual studio 调试器跳过特定的异常?

python - 麻烦递归地构建二元决策树python

C - 如何遍历哈夫曼树并生成相应的哈夫曼码?