Skip to content
Advertisement

Finding highest parent in a tree structure

I have a tree structure that is made out of the data below. I need a search algorithm to find the top leader when I put in anyone’s _id value, regardless of leader or child.

For example, if the input is "615e8215c3055d1addc216b0" (the id of Rahman) or "61164b4bc08f86505e7dcdd8" (the id of Aaron Aziz) it should return the id of “Aaron Aziz” as he is the leader.

The Tree Structure

The data structure has essentially a 2 level structure where each top-level entry has references to its immediate children. Notice that a child may appear again as leader (at the top level) so to specify deeper connections:

JavaScript

I’ve created a recursive function. But when I input a child without children, it returns the sibling instead of the parent.

JavaScript

How can I make it work?

Advertisement

Answer

I would suggest a function to first transform the structure, so each person can be looked up by id in constant time, giving their leader reference, children references and other properties.

So here is a makeGraph function to do just that, and then getTopLeader function to search that graph for a given child:

JavaScript

The graph variable will be useful for other lookup tasks as well.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement