Skip to content Skip to sidebar Skip to footer

How To Build The Path To Each Node In A Tree Recursively - Javascript?

My data structure will look like this: var tree = [ { id: 1, children: [] }, { id: 2, children: [ { id: 3,

Solution 1:

Beside the unclear taking of not directly involved parents, you could store the path as arrray and take it for each nested iteration.

functioniter(path) {
    path = path || [];
    returnfunction (o) {
        o.path = path.concat(o.id);
        if (o.children) {
            o.children.forEach(iter(o.path));
        }
    }
}

var tree = [{ id: 1, children: [] }, { id: 2, children: [{ id: 3, children: [] }] }];

tree.forEach(iter());
console.log(tree);
.as-console-wrapper { max-height: 100%!important; top: 0; }

Solution 2:

You can use recursion for this and check if input data is array or regular object.

var tree = [{ id: 1, children: [] }, { id: 2, children: [{ id: 3, children: [] }] }];

functionpaths(tree, parent = []) {
  if (Array.isArray(tree)) {
    tree.forEach(e =>paths(e, parent))
  } elseif (typeof tree == 'object') {
    parent = parent.concat(tree.id)
    tree.path = parent;
    if (tree.children) paths(tree.children, parent)
  }
}

paths(tree)
console.log(tree)

Solution 3:

You made a mistake

Your root node is an array, but all other nodes are objects.

This makes your program inconsistent and needlessly complex to handle the root node difference – the solution is to stop writing data using literals – you're bound to make mistakes like you did above

Instead, just make some simple data constructors and your complexities vanish into thin air

constNode = (id, ...children) =>
  ({ id, children })

constPathNode = (id, path, ...children) =>
  ({ id, path, children })

constaddPaths = ({id, children}, acc = []) =>
  PathNode (id, acc, children.map (child =>
    addPaths (child, [...acc, id])))
    
const tree =
  Node (0, Node (1),
           Node (2, Node (3)))

console.log (tree)
// { id: 0, children: [//   { id: 1, children: [ ] },//   { id: 2, children: [//     { id: 3, children: [ ] } ] } ] }console.log (addPaths (tree))
// { id: 0, path: [ ], children: [//   { id: 1, path: [ 0 ], children: [ ] },//   { id: 2, path: [ 0 ], children: [//     { id: 3, path: [ 0, 2 ], children: [ ] } ] } ] }

Post a Comment for "How To Build The Path To Each Node In A Tree Recursively - Javascript?"