gpt4 book ai didi

c++ - 从文件构造树

转载 作者:行者123 更新时间:2023-11-28 01:37:19 24 4
gpt4 key购买 nike

我正在开发一个 C++ 程序,它从文件重建二叉树。

除了它正在做的事情,我的程序还应该能够从文件中读取十六进制数。此外,指示节点没有子节点的标记是 -1,我希望它是一个字符(例如 #),但我在这方面没有取得多大成功。

谁能帮我解决这两个问题(从文件中读取十六进制并将 -1 替换为 # 作为标记?)。

#include <stdio.h>
#define MARKER -1

struct Node
{
int key;
struct Node* left, *right;
};

Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return (temp);
}

void deSerialize(Node *&root, FILE *fp)
{

int val;
if ( !fscanf(fp, "%d ", &val) || val == MARKER)
return;

root = newNode(val);
deSerialize(root->left, fp);
deSerialize(root->right, fp);
}

void preorder(Node *root)
{
if (root)
{
printf("%d ", root->key);
preorder(root->left);
preorder(root->right);
}
}

int main()
{
Node *root1 = NULL;
FILE *fp = fopen("tree.txt", "r");
deSerialize(root1, fp);

printf("preorder Traversal of the tree constructed from file:\n");
preorder(root1);

return 0;
}

例如,如果文件包含 1 2 4 -1 -1 5 -1 -1 3 -1 -1 它将显示 1 2 4 5 3

谢谢!

最佳答案

为什么不使用 ifsteam 而不是 FILE
为什么不使用 cout ( #include <iostream> ) 而不是 printf() ?
参见 this用于读取十六进制数(用于 ifstream ,不适用于 FILE )。

现在关于 #而不是 -1 .
只需将第一个字符读为 char , 检查它是 #还是不是。

关于c++ - 从文件构造树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48732258/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com