【发布时间】:2016-12-26 23:24:12
【问题描述】:
所以我正在尝试做一个在线作业(这不是为了课程学分,我是通过 coursera 自己承担)并且我对正在发生的事情感到非常困惑。
我们得到一个 2 行输入。第一行是树中的顶点数。第二行列出所有节点的父节点,-1 表示它是根节点。
例如,给定以下输入:
5
4 -1 4 1 1
第一行说总共有 5 个节点。第二行说节点 0 是节点 4 的子节点,节点 1 是根,节点 2 是节点 4 的子节点,节点 3 是节点 1 的子节点,节点 4 是节点 1 的子节点。
现在我只是尝试读取输入并将其存储在树结构中。
#include <iostream>
#include <vector>
using namespace std;
struct Node{
int key;
vector<Node*> children;
};
void display(Node* root){
cout << "My Value is " << root->key << endl;
cout << "My children are ";
for (int i = 0; i < root->children.size(); i++){
cout << root->children[i]->key << " ";
}
cout << endl;
for (int i = 0; i < root->children.size(); i++){
display(root->children[i]); //call display on all children
}
cout << endl;
}
int main(){
Node* root = NULL;
int numOfNodes;
cin >> numOfNodes;
int input;
vector<int> parents;
for(int i = 0; i < numOfNodes; i++){
cin >> input;
parents.push_back(input);
}
for(int i = 0; i < parents.size(); i++){
Node *newNode = new Node();
newNode->key = i;
if(parents[i] == -1){ //root node is indicated with a -1 in input
root = newNode;
}
for (int j = 0; j < parents.size(); j++){
if(parents[j] == i){
Node *childNode = new Node();
childNode->key = j;
newNode->children.push_back(childNode);
cout << "value " << newNode->key << " is now a parent of " << childNode->key << endl;
//delete childNode;
}
}
}
display(root);
return 0;
}
我添加了显示功能以查看我是否正确存储了树,这就是我迷路的地方。我添加的打印语句似乎有冲突。在main中,每当我添加一个childNode时,我都会添加一个cout,但是当我的程序进入显示功能时,似乎由于根节点的子节点的异常而丢失了childNodes。这是我的输出示例。
./treeheight
5
4 -1 4 1 1
value 1 is now a parent of 3
value 1 is now a parent of 4
value 4 is now a parent of 0
value 4 is now a parent of 2
My Value is 1
My children are 3 4
My Value is 3
My children are
My Value is 4
My children are
似乎在 main 中创建树的工作如我所愿,但是当我尝试在 display 中引用那些相同的节点时,出现了我不明白的错误。我原以为显示中的输出会显示为
My Value is 1
My children are 3 4
My Value is 3
My children are
My Value is 4
My children are 2 0
如果有人能对这里发生的事情有所了解,我将不胜感激。
【问题讨论】:
-
Node *newNode = new Node();-- 查看您的代码,如果if(parents[i] == -1)为假,您将不会存储此指针。因此是内存泄漏。