c - 将C二进制搜索树保存到txt文件

标签 c text-files binary-tree binary-search-tree

我正在做一个 C BST 库,我正在尝试做一个将二叉搜索树保存到文本文件中的函数。我对如何做很困惑。这是我的树结构:

struct Node {
    int value;
    struct Node *left;
    struct Node *right;
};

typedef struct Node TNode;
typedef struct Node *binary_tree;

树的创建:

binary_tree NewBinaryTree(int value_root) {
    binary_tree newRoot = malloc(sizeof(TNode));
    if (newRoot) {
        newRoot->value = value_root;
        newRoot->left = NULL;
        newRoot->right = NULL;
    }
    return newRoot;
}

向其中添加元素:

void Insert(binary_tree *tree, int val) {
    if (*tree == NULL) {
        *tree = (binary_tree)malloc(sizeof(TNode));
        (*tree)->value = val;
        (*tree)->left = NULL;
        (*tree)->right = NULL;
    } else {
        if (val < (*tree)->value) {
            Insert(&(*tree)->left, val);
        } else {
            Insert(&(*tree)->right, val);
        }
    }
}

我开始了这个功能,但我不知道该怎么做:

void savetree(binary_tree *tree, char * filename)
{
FILE *afile;
int remainn, counter, readsize, i;
int *bb;

afile = fopen(filename, "wb");
if (afile) {
    bb = calloc(sizeof(int), BBSIZE);  //BBSIZE =4096
    remainn = treesize(tree);
    counter = 0;
    while (remainn > 0) {
        if (remainn > BBSIZE) {
            readsize = BBSIZE;
        } else {
            readsize = remainn;
        }

这里是 treesize 函数:

int treesize( binary_tree tree )
{
    if( tree == NULL )
    {
        return (0) ;
    }
    else
    {
        return( 1 + treesize( tree->left ) + treesize( tree->right ) ) ;
    }
}

这个保存树函数没有完成,但我不确定如何完成它/如果我做的是正确的。

谢谢

最佳答案

嵌套的括号和树是同一事物的替代表示。

所以写一棵树很容易

   void writenode(Node *node)
   {
      printf("{");
      printf("%d ", node-.value);
      if(node->left)
         writenode(node->left);
      if(node->right)
         writenode(node->right);
      printf("}");
    }

阅读比较难。您必须检测格式错误的输入,并递归地构造子项。

关于c - 将C二进制搜索树保存到txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41253582/

相关文章:

java - 为什么将 k-ary 树表示为左子树、右兄弟树?

c++ - 如何将数字转换为十进制字符串?

python - (Python)无法打印文本文件的所有内容

python - 从文本文件中打印两个特定行(关键字)之间的多行

Python:使用与不带空格的字符串输入匹配的文本文件查找单词

c - 树问题中的递归函数

algorithm - 如何计算二叉树中右 child 的数量?

c - strcmp() 给出段错误 : 11 and pointer from integer warning

将CPU改为GPU并运行OpenCL程序遇到调用模糊提示

c++ - 无法理解代码/函数调用