How to get to the root of the structure?

  • 0
    There is a tree structure - a graph.

    The user is at a specific node within the graph. The node does not have any unique id or name to distinguish it from others.

    How to return the path from this node to the root of the tree?

    Structure

    [
      {
        "name": "Root 1",
        "children": [
          {
            "name": "X",
            "children": [
              {
                "name": "Y",
                "children": [
                  {
                    "name": "Z",
                    "children": []
                  }
                ]
              }
            ]
          }
        ]
      },
      
      {
        "name": "Root 2",
        "children": [
          {
            "name": "X",
            "children": [
              {
                "name": "Y",
                "children": [
                  {
                    "name": "Z",
                    "children": []
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
    JavaScript Luke Klein, May 3, 2019

  • 4 Answers
  • 0
    using a recursive function call that will stop when it reaches the value you need
    Anonymous

  • 0
    Jackson Haynes

  • 0
    If you have the ability to change the structure (at least in a local variable), then do not try to come up with a solution that will break the minds of you and those who will maintain this code.

    Create a structure that is convenient for you based on the data - for example, you can extend the object with the parent field with a link to the parent, and then walking up the tree will be as simple as possible.

    As a rule of thumb, if the algorithm gets complex, then you have chosen a bad data structure. If your problem does not have a simple solution, then change the data model and get a simpler solution.
    Chase Jefferson

  • 0

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!