I'm trying to populate a tree as below.
m
is the number of inputs and s
is the data for the head node.
c
is the head node and the inputs that follow are parent-child nodes. Each node has a list of children.
Now, calling addNode
to always start from the top of the tree is slow for what I'm doing. Instead, I make addNode
return a reference to the to
node that it adds to the tree. I maintain a map iNode
of to - TreeN
so that I can pass a reference to the from
node to addNode
instead of passing it the head node.
I think what happens is when a TreeN
's vector resizes, the objects in it are copied to a new vector in memory and the reference to the nodes I had in iNode
are to now deallocated memory. I'm not sure though, fairly new to Cpp.
How would I get this to work the way I want it to?
class TreeN {
public:
int d;
vector<TreeN> chld;
bool operator==(const TreeN &o) {
return o.d == d;
}
};
TreeN& addNode(TreeN &root, int &from, int &to) {
cout << "f: " << from << " t: " << to << " p: " << root.d << endl;
if (root.d == from) {
root.chld.push_back(TreeN{to});
return root.chld[root.chld.size() - 1];
}
else {
for(auto &c : root.chld) {
return addNode(c, from, to);
}
}
}
int main(int argc, const char** argv) {
int m, s;
cin >> m >> s;
TreeN c = {s, vector<TreeN>{}};
map<int, TreeN&> iNode;
iNode.insert(pair<int, TreeN&>(c.d, c));
while (m--) {
int a, b;
cin >> a >> b;
map<int, TreeN&>::iterator itA = iNode.find(a);
map<int, TreeN&>::iterator itB = iNode.find(b);
if (itA != iNode.end()) {
cout << "here " << itA->first << endl;
TreeN &n = addNode(itA->second, a, b);
cout << n.d << endl;
if (itB == iNode.end()) iNode.insert(pair<int, TreeN&>(b, n));
} else {
iNode.insert(pair<int, TreeN&>(b, addNode(c, a, b)));
}
}
printTree(c);
}
Input:
4 1
1 2
1 3
2 3
3 2
This code fails and gives the following output:
here 1
f: 1 t: 2 p: 1
2
here 1
f: 1 t: 3 p: 1
3
here 2
f: 2 t: 3 p: 0 (should say 2)
Segmentation fault (core dumped)