An algorithm which uses recursion goes like this:
printNode(Node node)
{
printTitle(node.title)
foreach (Node child in node.children)
{
printNode(child); //<-- recursive
}
}
Here's a version which also keeps track of how deeply nested the recursion is (i.e. whether we're printing children of the root, grand-children, great-grand-children, etc.):
printRoot(Node node)
{
printNode(node, 0);
}
printNode(Node node, int level)
{
printTitle(node.title)
foreach (Node child in node.children)
{
printNode(child, level + 1); //<-- recursive
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…