void BinTree::toArrayHelper(const Node* current,NodeData* bsarray[], int &index) const { if(current->left != NULL){ toArrayHelper(current->left,bsarray, index); } bsarray[index] = current->data; index++; if(current->right != NULL){ toArrayHelper(current->right, bsarray,index); } delete [] current; }
//------------------------------------------------------------------------------ // bstreeToArray // A routine fills an array of NodeData* by using an inorder traversal // of the tree. It leaves the tree empty. // Assumes array is equal to or larger than tree and full of NULLs. void Tree::bstreeToArray(NodeData *nd[]) { if (_root != NULL) { // beginning of the array int index = 0; toArrayHelper(_root, nd, index); //_root = NULL; //_size = 0; } }
int Tree::toArrayHelper(Node * &curr, NodeData *nd[], int index) { if (curr != NULL) { // Inserts left subtree into array first // int child is number of how many objects were inserted into array int child = toArrayHelper(curr->left, nd, index); // Adds current index to child index += child; // Inserts self into array nd[index] = curr->data; // Inserts right subtree into array child += toArrayHelper(curr->right, nd, index + 1); // Removes pointer to NodeData // delete curr; // curr = NULL; // Returns increment of left and right childs return child + 1; } else { return 0; } }
void BinTree::bstreeToArray(NodeData* bsarray[]){ index = 0; toArrayHelper(root,bsarray,index); root = NULL; }