How can you add all elements of a binary tree to an array using recursion?

Tree structure

struct node { int data; node* left; node* right; }; 
  • and how the tree is implemented? - Komdosh
  • struct node {int data; node * left; node * right; }; - Sergej Koflik

1 answer 1

In fact, you need to bypass all the elements of the tree. Go around, for example, first the root, and then - the hand - two child subtrees. Or first subtrees, and then the root. Or one subtree, root, second ...

 void addToArray(node* root, array& a) { Добавить root->data в a if (root->left) addToArray(root->left,a); if (root->right) addToArray(root->right,a); } 

Like that.

Update

For a vector:

 void addToArray(node* root, vector<int>& a) { a.push_back(root->data); if (root->left) addToArray(root->left,a); if (root->right) addToArray(root->right,a); } 

For a C-array (select the place yourself):

 void addToArray(node* root, int * a, size_t& idx) { a[idx++] = root->data; if (root->left) addToArray(root->left,a,idx); if (root->right) addToArray(root->right,a,idx); } 

Call:

 size_t idx = 0; addToArray(root,a,idx); 
  • Thanks for the answer. But in my case, it is specifically in writing elements to a binary tree. I work around correctly, through cout everything is displayed correctly, but I cannot add to the array. - Sergej Koflik
  • Which array? Vector, or is it exactly an array of type int a[] ? - Harry
  • It is mandatory an array. ... Fatigue affects such a trifle not to do it yourself. Thanks for the help :) - Sergej Koflik