Help determine the number of nodes at each level of the tree.

#include <iostream> using namespace std; struct Node { int info; Node *left; Node *right; } *tree; void Add(int a, Node **tree) { if ((*tree) == NULL) { (*tree) = new Node; (*tree)->info = a; (*tree)->left = (*tree)->right = NULL; return; } if (a > (*tree)->info) { Add(a, &(*tree)->right); } else { Add(a, &(*tree)->left); } } void Print(Node *tree) { if (tree == NULL) { return; } cout << tree->info << endl; Print(tree->left); Print(tree->right); } int main() { int n; int info; cout << "Enter number of elements: "; cin >> n; for (int i = 0; i < n; i++) { cout << "Enter " << i + 1 << " elements: "; cin >> info; Add(info, &tree); } cout << "Tree: " << endl; Print(tree); system("pause"); return 0; } 
  • And what you actually can not? Formulate a problem / question. - Kromster
  • Try to write more detailed questions. Explain exactly what you see the problem, how to reproduce it, what you want to get as a result, etc. - Nicolas Chabanovsky

1 answer 1

In your Print function, add (or rewrite, write a new function) the depth level, and save the results when traversing the tree. I would do with a map , like this:

 void Count(Node* tree, map<int,int>&m, int level) { m[level]++; if (tree->left) Count(tree->left,m,level+1); if (tree->right) Count(tree->right,m,level+1); } map<int,int> m; Count(tree,m,0); for(auto i: m) { cout << "На уровне " << i.first << " находится " << i.second << "узлов.\n"; } 
  • there are errors in the declaration is incompatible with "<error-type Count"> function - Neon
  • @Neon ideone.com/dntPJJ - where? - Harry
  • The first line - Neon
  • @Neon Once again - I provided a link to the full code, compiled, worked. See what is wrong with you - maybe you were somehow sealed during the transfer? Once again - here: ideone.com/dntPJJ - fully compiled and executed program. - Harry