繁体   English   中英

二叉树-在没有count参数的情况下递归计算级别上节点数量的方法(Java)

[英]Binary Tree - Method to recursively count the number of nodes on a level without a count parameter (Java)

我希望拿一些用Java为二进制树类编写的代码,并从参数中删除count参数,但要使整个过程保持递归。

因此,给定一个具有以下变量的类:

 public class BinaryTree<E> {

  protected E data;
  protected BinaryTree<E> left,right;

我该怎么做:

public int levelCount(int count, int level){
 if (data == null) {return 0;}
 if (count == level) {return 1;}
 else {
  return this.getRight().levelCount(count+1,level) + this.getLeft().levelCount(count+1,level);
  } 
}

这应该(并且确实)返回二进制树任何给定级别的节点数。

因此,使用树“ thatTree”看起来像:

     2
   /    \
  6      3
 / \    / \
4   5  7   10 

thatTree.levelCount(0)返回1,那个Tree.levelCount(1)返回2,那个Tree.levelCount(2)返回4

为什么不传递单个参数,在每个递归中减去1,并在它为0时结束? 就像是:

public int levelCount(int level){
  if (data == null || level < 1) {return 0;}
  if (level == 1) {return 1;}
  else {
    return this.getRight().levelCount(level-1) + this.getLeft().levelCount(level-1);
  } 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM