Javier
Javier

Reputation: 2105

How to compute the distance between a leaf and the root node in a tree structure

I'm trying to create a tree structure. But I don't know how to use recursive methods.

I'm loading an array that contains info and children.

What I would like to know is, how far down is a node from the root?

For exmaple:

const data = [
    {id: 1, title: 'foo', children: [
        {id: 11, parentId: 1, title: 'bar',},
        {id: 12, parentId: 1, title: 'baz', children: [
            {id: 121, parentId: 12, title: 'qux'},
            {id: 122, parentId: 12, title: 'quz'}
        ]},
        {id: 13, parentId: 1, title: 'corge'}
    ]}
];

Upvotes: 0

Views: 211

Answers (1)

FZs
FZs

Reputation: 18609

You can write a recursive method for that:

const data = [
  {id: 1, title: 'foo', children: [
    {id: 11, parentId: 1, title: 'bar'},
    {id: 12, parentId: 1, title: 'baz', children: [
      {id: 121, parentId: 12, title: 'qux'},
      {id: 122, parentId: 12, title: 'quz'}
    ]},
    {id: 13, parentId: 1, title: 'corge'}
  ]}
];

function findDistance(data, id) {
  for(const elem of data){
    if(elem.id === id) return 0
    if(!elem.children) continue
    const value = findDistance(elem.children, id)
    if(!Number.isNaN(value)) return value + 1
  }
  //Not found, return NaN
  return NaN
}

console.log(findDistance(data, 1))   //0
console.log(findDistance(data, 12))  //1
console.log(findDistance(data, 122)) //2
console.log(findDistance(data, 13))  //1
console.log(findDistance(data, 0))   //Not found, NaN

Upvotes: 1

Related Questions