【发布时间】:2017-07-12 07:58:53
【问题描述】:
我编写了一个代码来打印和查找 n 叉树中节点的总和,但我得到一个错误并且我无法修复它。
#include <iostream>
#include <queue>
using namespace std;
class Node
{
public:
Node(int input)
{
this->data = input;
}
vector<Node*> children;
int data;
};
void print(Node *root)
{
if (root == NULL)
return;
queue<Node *> q;
q.push(root);
int count = 0;
while (q.size() != 0)
{
Node *node = q.front();
cout << node->data << " ";
q.pop();
int sum = 0;
for (unsigned int i = 0; i < node->children.size(); i++)
{
q.push(children[i]);
sum += (children[i]);
}
cout << " - ";
}
cout << "Sum: " << cout;
}
int main()
{
tree->children.push_back(new Node(16));
tree->children.push_back(new Node(96));
tree->children.push_back(new Node(8));
tree->children.push_back(new Node(10));
tree->children.push_back(new Node(22));
tree->children.push_back(new Node(9));
tree->children.push_back(new Node(100));
tree->children.push_back(new Node(1));
tree->children.push_back(new Node(51));
tree->children.push_back(new Node(70));
cout << "Root: " << tree->data << endl << "Children:" << endl;
for (unsigned int i = 0; i < 10; i++)
{
cout << tree->children[i]->data << " ";
}
cout << endl;
print (tree);
}
错误:'children' 未在此范围内声明 q.push(儿童[i]); 我该如何解决? 这个错误是什么意思?
【问题讨论】:
-
也许你的意思是
node->children?而且意思很明确:print函数中没有变量children。 -
treeinmain也是未知的。
标签: c++ pointers tree n-ary-tree