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
  •  | 
  •  

문제

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.

도움이 되었습니까?

해결책

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);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top