Traversing a tree of objects in c#

前端 未结 2 1500
时光说笑
时光说笑 2020-12-02 11:19

I have a tree that consists of several objects, where each object has a name (string), id (int) and possibly an array of children that are of the s

2条回答
  •  暖寄归人
    2020-12-02 12:11

    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
      }
    }
    

提交回复
热议问题