如何将二叉树存储入文件以便它能方便被重构

9 篇文章 0 订阅

一棵没有特定顺序的二叉树,如何将二叉树存储入文件以便它能方便被重构?

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;
}



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值