how to find the number of nodes at level x of the binary search tree ( with restrictions )

StackOverflow https://stackoverflow.com/questions/23468501

  •  15-07-2023
  •  | 
  •  

Question

Hello the problem I am having with this question is making a function that uses only the binary tree head pointer and the desired level(height) of the tree, something like:

int countLevel(tree_type tree, int n)

I've been thinking about it for some time now and I can't seem to find a solution without having to add another value to the function to represent the running number/Height of the tree ( I think there is a way to represent it without changing the function itself? )

P.S. I am coding it on C at the moment.

Was it helpful?

Solution

Something like this should work, assuming tree_type is a node pointer:

int countLevel(tree_type tree, int n) {
   if (tree == 0) return 0;
   if (n == 0) return 1;
   return countlevel(tree->left, n - 1) + countlevel(tree->right, n - 1);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top