java - 从递归方法返回时需要帮助

标签 java algorithm data-structures binary-tree traversal

我正在尝试跟踪二叉树(不是二叉搜索树)中节点的路径。给定一个节点,我尝试打印从根开始的路径值。

alt text

我写了下面的程序。

package dsa.tree;

import java.util.Stack;

public class TracePath {
    private Node n1;

    public static void main(String args[]){
        TracePath nodeFinder = new TracePath();
        nodeFinder.find();
    }

    public void find(){
        Tree t = getSampleTree();
        tracePath(t,n1);
    }

    private Tree getSampleTree() {
        Tree bsTree = new BinarySearchTree();
        int randomData[] = {43,887,11,3,8,33,6,0,46,32,78,76,334,45};
        for(int i=0;i<randomData.length;i++){
            bsTree.add(randomData[i]);
        }
        n1 = bsTree.search(76);
        return bsTree;
    }

    public void tracePath(Tree t, Node node){
        trace(t,node);
    }

    Stack<Node> mainStack = new Stack<Node>();

    public void trace(Tree t, Node node){
        trace(t.getRoot(),node);
    }

    private void trace(Node parent, Node node){
        mainStack.push(parent);
        if(node.data == parent.data){
            for(Node iNode:mainStack){
                System.out.println(iNode.data);
            }
            return;
        }
        if(parent.left != null){
            trace(parent.left, node);
        }
        if(parent.right!=null){
            trace(parent.right, node);
        }
        mainStack.pop();
    }
}

我正在正确获取输出。但有点乱。如果您看到方法 trace(Node, Node),我正在打印我不应该做的值。我希望跟踪方法正确完成。至少,我应该在遇到 if 条件的阶段终止递归结构。

请指教。

最佳答案

好的,一旦找到节点,就需要终止递归。很简单。更改您的跟踪方法以返回一个 boolean 值,告诉我们是否找到了节点。这样,我们在找到节点后立即返回树。

private boolean trace(Node parent, Node node){
    mainStack.push(parent);
    if(node.data == parent.data){
        for(Node iNode:mainStack){
            System.out.println(iNode.data);
        }
        return true;
    }
    if(parent.left != null){
        if (trace(parent.left, node)) return true;
    }
    if(parent.right!=null){
        if (trace(parent.right, node)) return true;
    }
    mainStack.pop();
    return false;
}

关于java - 从递归方法返回时需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2247063/

相关文章:

java - 使用 sphinx4 识别所有英语单词

java - 尝试在 Java 中使用 SunPKCS11 和 NSS 启用 FIPS 模式

java - 寻找更好的锯齿形阵列方法

java - Java 中的全局 ArrayList 中未添加值

转置数据帧后 R 变量类型发生变化

algorithm - 对任意大的整数使用什么数据结构?

java - 跨多个 Activity 重用功能

java - 同一张表上的左连接

r - 通过最小化 R 中的方差对数据进行分组

java - 从字符串中提取操作数和运算符