【问题标题】:Recursive method to get the number of occurences of an element in a binary tree获取二叉树中元素出现次数的递归方法
【发布时间】:2016-10-31 06:40:59
【问题描述】:

嗨。我无法以递归格式编写此方法(在照片中)。该方法获取给定元素在二叉搜索树中的出现次数。 为了递归地解决这个问题,我尝试使用同名的私有辅助方法来实现它,如下所示:

public int count(){
count = 0;
if (root == null)
    return count;
return count (root.getInfo());

private int count(T element){
(Basically the same code you see in the photo)
}

但我最终遇到了溢出错误。你介意看看并告诉我如何递归地构造这个方法吗?

干杯,谢谢。

【问题讨论】:

  • root 不是函数的局部变量,这可能是错误的原因。您想要一个递归函数,但您使用的循环没有意义,并且 if 条件中的“root = root.getLeft()”也没有意义。

标签: recursion tree binary-search-tree


【解决方案1】:

暂定的实现可能如下所示。

public int count(T element, T root){
   if(element == null) {
      return 0;
   }
   int count = 0;
   int compare = element.compareTo(root.getInfo());
   if(compare == 0){
      count++;
   }
   count += count(element, root.getLeft());
   count += count(element, root.getRight());
   return count;
}

count(item, root);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-20
    • 2014-10-17
    • 1970-01-01
    • 2016-07-17
    • 2018-10-30
    • 2023-01-22
    • 1970-01-01
    相关资源
    最近更新 更多