【问题标题】:Keep count of marked nodes in recursive method以递归方法保持标记节点的计数
【发布时间】:2016-02-27 16:25:22
【问题描述】:

我有一个遍历二叉搜索树的递归方法。每次它访问具有关键属性的节点时,它都会获取该节点并将其插入到新的 BST 中。我的问题是我需要计算有多少节点具有关键元素。我很难用递归方法做到这一点。有谁知道如何在递归方法中实现“计数器”。我还在下面发布了我的代码。

public BookBST TraverseInOrder_Pblshr(Node localRoot, String key, BookBST B){
    if (localRoot!=null){

        TraverseInOrder_Pblshr(localRoot.leftChild, key, B);

        if(localRoot.B1.GetPublisher().equals(key)){            // if node matches key
            B.insert(localRoot.B1,3);                       // insert into BST (using publisher to order)
            //System.out.println(localRoot.B1.GetPublisher()+ "    this is item has been inserted into subtree");
            //System.out.println(localRoot.B1.GetTitle());
        }

        TraverseInOrder_PubYr(localRoot.rightChild, key, B);
    };
    return B;
}

【问题讨论】:

  • 为什么计算这些东西是TraverseInOrder_Pblshr 方法的工作? (或者..._PubYr方法,不管它是什么。)调用者以B的引用开始,所以它可以保存B的大小,然后运行这个方法,然后比较B的新大小后。区别在于拥有密钥的项目数量。
  • 想想看……你为什么要返回B?调用者已经拥有它。

标签: java recursion counter


【解决方案1】:

有谁知道如何在递归方法中实现“计数器”。

是的。如果递归方法是void,则只需添加int 类型的参数count 并设置返回类型int。要增加计数器,只需执行count++;。当您递归调用该方法时,只需这样做

count = recursiveMethod(count);

在您的情况下,该方法不是void,这使得它稍微困难一些。一个技巧是添加一个int[] 类型的额外参数。但是,我建议为此使用私有辅助方法。不要用这个额外的参数暴露可怕的签名。

public BookBST TraverseInOrder_Pblshr(Node localRoot, String key, BookBST B){
    return helper(Node localRoot, String key, BookBST B, new int[1]);
}

private BookBST helper(Node localRoot, String key, BookBST B, int[] counter) {
    // You should call **this** method recursiviely, not TraverseInOrder_Pblshr. E.g.
    // helper(localRoot.leftChild, key, B, counter);
    // To increment the counter, just do counter[0]++;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多