How do I get a tree branch?

  • 0
    for example there is such a tree: (only idlers)
    31940649
      31951793
      31951796 
        31951905 
        31951908
        31951911
        31951914
        31951917
      31951799
        31951920
        31951923
        31951926
        31951929
        31951932


    and I need a branch for id 31951932 (the last one), and then I should get this:
    31940649
      31951799
        31951932

    I can't figure out how to do it.

    ps there is no logic in id's, it is useless to parse them.
    JavaScript Anonymous, Dec 3, 2020

  • 2 Answers
  • 0
    1. Looking for a parent and unshift.

    2. Repeat while there is a parent.
    Anonymous

  • 0
    If, as in your example, you are given indented text, then you can do this:



    Read line by line and break the line into a number and how many spaces are in front of it.

    Create an array where you will store "active" ancestors for all levels.

    Overwrite the value at the index "how many spaces at the beginning of the line".

    When finding your desired index, output this array (up to the current number)

    In fact, this array is the stack where you keep the current branch.



    Here's an example:

    1
    2
    3
    4




    Let's say you need ancestors for id = 4.

    Read "1". Array {1,0,0 ...}. Have read "2". Array {1, 2, 0 ...}. Read "3". Array {1, 3, 0 ...}. Read "4". The array has become {1, 3, 4}. 4 - the required element, we display the branch 1-3-4.



    If your padding is 2, then divide the number of spaces by 2 to get the index. Or you may have tab characters in there - count them. The solution does not work if the format is not consistent and different levels may have different indents. But here you can read the current depth. It is also necessary to store in the array how many spaces at the beginning of each level. If the new line is indented more than the line at the current level, then we increase the depth and put the line into the array. If it has less, then decrease the depth until the indents are the same as the line at this level.



    If you need to do this operation quickly and many times, then it is better to translate this string entry into a real tree once, with links to the parent for each id: each time you write an id to the array, refer to the previous id in the array as a parent.
    Dominick Webster

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