gpt4 book ai didi

每个节点具有恒定时间的 C++ 树

转载 作者:行者123 更新时间:2023-11-28 03:40:23 29 4
gpt4 key购买 nike

我正在处理树。每个节点都有带有 Tree * 值的对象。我读取的数据如下所示:

1
2
2
...

这意味着,将 1 作为 0 的子节点,将 2 作为 1 的子节点,将 3 作为 o 2 的子节点。在常规形式中:将 x 作为 i-1 的子节点,其中 i 是行数。
我决定做树,看起来像:

class Tree {
public:
int value;
stack <Tree*> children;

Tree ();
Tree (int x) {value = x;}
void wypisz();
};

所以现在当我读取输入时,我需要做一些事情(但它不起作用):

int n,x;
scanf("%d",&n);
Tree **tab;
tab = (Tree **) malloc(sizeof(Tree*)*n);
Tree *n = 0;
tab[0] = new Tree(0);
for(int i=1;i<n;++i) {
scanf("%d",&x);
n = new Tree(x);
tab[i] = n;
tab[i-1]->children.push(n);
}
delete n;

所以我需要 n = new Tree(x);是一个指向树的新对象的指针,并添加这个指针在 [i] 位置制表并将此指针添加到 tab[i-1] 元素的子元素。怎么了这个代码?这些行无法编译:

n = new Tree(x);
tab[i] = n;

错误:

  1. line: Value ot type "Tree *" cannot be assigned to an entity of type "int".
  2. line: Value ot type "int" cannot be assigned to an entity of type "Tree *".

最佳答案

首先将n 声明为int。稍后您将 n 声明为 Tree*

这两个声明冲突,因为它们试图用两种不同的类型声明同一个变量。为避免冲突,请使用两个不同的变量名。

关于每个节点具有恒定时间的 C++ 树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9454765/

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