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

不羁的心 提交于 2021-01-08 05:29:40

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/26620908/binary-tree-method-to-recursively-count-the-number-of-nodes-on-a-level-without

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!