I am unsure how to go about solving this. I am almost certain solving this recursively is the way to go but I'm not quite sure how to go about it. I have a structure with a string and vector of said structure. The parent is the name and the vector are the children.
Structure Code:
1 2 3 4 5 6 7 8 9
struct TreeNode
{
string data;
vector<TreeNode *> children;
TreeNode(string data)
{
this -> data = data;
}
};
I know i need a for loop but i cant seem to figure out the logic. I've been trying to draw pictures to help visualize it but to no avail. Can anyone help send me in the right direction?
Wow that was a very thorough answer! Thank You! Could you help explain the depth part? I believe that was what was causing me issues in my logic. Thanks again!!
> Could you help explain the depth part?
> I believe that was what was causing me issues in my logic.
The depth is the depth of recursion (the level of the node in the sub-tree). Each time we descend one level down the tree, we pass the depth as current depth + 1 for( const TreeNode* pchild : p->children ) list_subtree( pchild, depth+1 ) ;
The depth of the node is then used to give the output a tree-like look, with the data of the node indented by the depth of the node; so that we get an output like this: