一棵没有特定顺序的二叉树,如何将二叉树存储入文件以便它能方便被重构?
Here is a tree. It's a binary tree but in no particular order. How do you write this tree to a file so that it can be reread in an reconstructed exactly as shown?
有特定顺序的二叉树只适用于完全二叉树。对于这个问题,他们想要的可能是存储每个元素(如下标i代表的元素)于数组中,它的孩子在2i和2i+1的位置。如果没有左或者右孩子,让对于的下标空间为空(也可以为特定字符,表示为空)。利用这个数组很容易重建二叉树。
An ordered (pre/post/in) works only for a complete binary tree. For the question, perhaps what they want is to store each element (say at i index) in an array and it's child at 2i and 2i+1 position. If it does not have a left/right child,
leave the corresponding index empty.
From this array, it is easy to reconstruct any binary tree.
struct node{
int data;
node* left;
node*right;
};
node * re_construct(int i){
if (a[i]==NULL)
return NULL;
node *new_root = malloc(sizeof(node));
new_root->data = a[i];
new_root->left = re_construct(2*i);
new_root->right = re_construct(2*i+1);
return new_root;
}