简体   繁体   English

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

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

I'm looking to take some code I've written in Java for a binary tree class and remove the count parameter from the arguments, but keep the whole thing recursive. 我希望拿一些用Java为二进制树类编写的代码,并从参数中删除count参数,但要使整个过程保持递归。

So, given a class with these variables: 因此,给定一个具有以下变量的类:

 public class BinaryTree<E> {

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

How could I do that for: 我该怎么做:

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);
  } 
}

This should (and does) return the number of nodes at any given level of the binary tree. 这应该(并且确实)返回二进制树任何给定级别的节点数。

So with a tree "thatTree" which looks like: 因此,使用树“ thatTree”看起来像:

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

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

Why not pass a single argument, subtract 1 on each recursion, and end when it is 0? 为什么不传递单个参数,在每个递归中减去1,并在它为0时结束? Something like: 就像是:

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