简体   繁体   中英

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.

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:

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

thatTree.levelCount(0) returns 1, thatTree.levelCount(1) returns 2, thatTree.levelCount(2) returns 4

Why not pass a single argument, subtract 1 on each recursion, and end when it is 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);
  } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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