I was going through the question Tree Nodes Getting Lost and thought it woudl be a good exercise to do in c++11.
I came with the code below. But the Root element is not connecting to the rest of the nodes and I can't find why.
#include <iostream>
#include <vector>
#include <array>
struct Node
{
int key;
std::vector<Node> children;
Node(int k)
{
key = k;
}
void Add(Node n)
{
children.push_back(n);
}
void display()
{
std::cout << "My value is " << key << std::endl;
std::cout << "My " << children.size() << " kid(s) are : " << std::endl;
for( auto n : children)
{
n.display();
}
}
};
int main()
{
constexpr int numNode = 5; // for
std::array<int, numNode> numbers = { 4, -1, 4, 1, 1 };
std::vector<Node> nodesStorage;
for (int i = 0 ; i < numNode ; i++)
{
nodesStorage.push_back(Node(i));
}
nodesStorage.push_back(Node(-1));
for (int i = 0 ; i< numNode ; i++)
{
if(numbers[i] == -1) // the root
{
nodesStorage[numNode].Add(nodesStorage[i]);
}
else
{
nodesStorage[numbers[i]].Add(nodesStorage[i]);
}
}
nodesStorage[1].display();
nodesStorage[numNode].display();
return 0;
}
Aucun commentaire:
Enregistrer un commentaire