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; }; 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; }; 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); int a[] ? - HarrySource: https://ru.stackoverflow.com/questions/826382/
All Articles