To get paths from a n-ary tree, we can use depth-first search algorithm. We can start from the root node and traverse all the child nodes recursively, while keeping track of the current path. When we reach a leaf node, we add the current path to the result.
Here's the example code:
index.tsx489 chars28 lines
In this code, we define a TreeNode
class to represent n-ary tree nodes, which contains a value and an array of child nodes.
The getPaths
function takes the root node as an argument and returns an array of paths. The dfs
function is a helper function that takes the current node, the current path, and the result array.
Inside dfs
, we add the current node value to the path and check if the node is a leaf node. If it is, we add the current path to the result. If not, we iterate over each child node and call the dfs
function recursively.
Finally, we remove the last element from the path array using pop
method.
Here's an example usage:
index.tsx191 chars4 lines
This will output an array of four paths as expected.
gistlibby LogSnag