get paths from nary tree without root in javascript

To get all the paths from an n-ary tree without the root node in JavaScript, we can use a depth-first search (DFS) algorithm.

Assuming we have a class Node that represents a node in the tree with an array of children, the following function will return an array of arrays representing all the paths from the n-ary tree without the root node:

index.tsx
function getPathsFromNaryTree(node) {
  const paths = []
  
  function dfs(currNode, path) {
    // Base case: if current node is null, return
    if (!currNode) {
      return
    }

    // Add current node to path
    path.push(currNode)

    // If current node has no children, add path to list of paths
    if (currNode.children.length === 0) {
      paths.push([...path])
    } else {
      // DFS on all children
      for (let child of currNode.children) {
        dfs(child, path)
      }
    }

    // Remove current node from path
    path.pop()
  }

  // Starting DFS on all children of the root node
  for (let child of node.children) {
    dfs(child, [])
  }

  return paths
}
690 chars
34 lines

This function starts the DFS on all children of the root node and then recursively traverses the tree. It keeps track of the current path and adds it to the list of paths when it reaches a leaf node. When the function returns, it will have generated an array of arrays representing all the paths from the n-ary tree without the root node.

gistlibby LogSnag