Good day. There is a binary search tree. It is necessary to balance it, but it is impossible to make an array of objects from the tree. In theory, it should be something like this, but for some reason, not all elements fall into an array.

void GetMassive(int &n, tree_node * root, DataM *M) { if (root!=NULL) { GetMassive(n,root->left,M); M[n++] = root->info; GetMassive(n,root->right,M); } } 
  • I think instead of while should be if - diraria
  • It is also advisable to either make int n a global variable, or replace int n with int &n - diraria
  • one
    The whole problem was this. It was necessary to transfer through the pointer .. - TorSen

1 answer 1

There are two problems in your code.

  1. while (root!=NULL) . If the code goes inside this cycle, then it will not exit it, because the value of the root variable does not change inside the cycle. It is necessary to replace while with if .
  2. The parameter of the function int n . Consider the very first function call, n == 0 . Next, the line GetMassive(n,root->left,M); . If the left subtree is not empty, then the first few elements of the array M will be filled. But in the very first function call still n == 0 . Therefore, the element M[0] overwritten. It is necessary either to make a global variable, or to replace int n by int &n .

Possible Solution:

 #include <iostream> typedef int DataM; struct tree_node { DataM info; tree_node *left = nullptr; tree_node *right = nullptr; tree_node(DataM info) : info(info) {} }; void GetMassive(tree_node *root, DataM *M, int &n) { if (root != nullptr) { GetMassive(root->left, M, n); M[n++] = root->info; GetMassive(root->right, M, n); } } void GetMassive(tree_node *root, DataM *M) { int n = 0; GetMassive(root, M, n); } int main() { tree_node *left = new tree_node(1); tree_node *right = new tree_node(4); tree_node *right_left = new tree_node(3); tree_node *right_right = new tree_node(5); tree_node *root = new tree_node(2); right->left = right_left; right->right = right_right; root->left = left; root->right = right; DataM array[5]; GetMassive(root, array); for (int array_i : array) { std::cout << array_i << std::endl; } return 0; } 
  • one
    Yes, I corrected the tip above :) Thank you. - TorSen