BST preorder traversal and writing tree content to temporary array
I'm trying to write binary search tree's content to temporary array in order to use in main. However I'm not sure how to do it... I have tried something like this:
void Book::preorder(TreeNode *ptr, Person &temp[], int x)
{
if(ptr!=NULL)
{
temp[x].name=ptr->item.name;
x++;
preorder(ptr->left, temp, x);
preorder(ptr->right, temp, x);
}
}
And, it gives following errors:
declaration of 'temp'a as array of references
no match for 'operator[]' in '((Book*)this->Book::temp[x]'
no matching function for call to 'Boo开发者_运维问答k::preorder(TreeNode*&, Person&, int&)'
Try this:
void Book::preorder(TreeNode *ptr, Person temp[], int x)
{
if(ptr!=NULL)
{
temp[x].name=ptr->item.name;
x++;
preorder(ptr->left, temp, x);
preorder(ptr->right, temp, x);
}
}
void Book::preorder(TreeNode *ptr, Person temp[])
{
if(ptr!=NULL)
{
temp[globX].name=ptr->item.name;
temp[globX].phoneNumber=ptr->item.phoneNumber;
globX++;
preorder(ptr->left, temp);
preorder(ptr->right, temp);
}
}
is my final code. And i'm pretty sure that it works... Previous code has some kind of logic error. Using global variable (i know it's not recommended) I figured it out.
This is perhaps too late, however I believe, is good to point out here. What the aforementioned answers suggest over here solely relate to serializing a binary (search) tree. Imagine you wish to reconstruct the tree later given its serialized version. You have to mark up the leaves so that when you attempt to re-build the tree, it is clear which node is a child of another one. To achieve this, simply add NULL references to the array (or list) when you encounter a leaf node. Yet, when going one level up, add yet another NULL reference to the array. In other words, before returning from each recursion, simply add a NULL to the array that has been passed in to the method. This way, any move one level up will yield insertion of a NULL to the array. When reconstructing the list, add the elements to a stack as you read them from the array left-to-right. Once hitting a NULL reference, you pop() the topmost object from the stack and left the next peek() of the stack to point to it as one of its children. Continue to the next element within the array and repeat the same procedure. There are perhaps better ways to further optimize this approach but this is what was on top of my head to mention. Hope it helps.
精彩评论