Original link: leetcode-cn.com/problems/n-…

Answer:

  1. The first thing to do with recursion is to think about what to do if the current recursive function is running the NTH recursion.
  2. The first thing to consider is that, assuming that the last node of the iteration is null, we set the termination condition for the recursion.
  3. The next thing you need to do is traverse the n-tree, which means you need to call a recursive function that continues to traverse all the children.
  4. In this recursion, the logic of the current node is processed, that is, the value of the current node is stored. Since it is a sequential traversal, the storage time is before traversal of child nodes.
/** * // Definition for a Node. * function Node(val, children) { * this.val = val; * this.children = children; *}; * /
function recursion(node, res) {
  // If the node is empty, exit
  if(! node) {return;
  }

  // Sequential traversal, which stores the value of the current node before the child node is traversed
  res.push(node.val);

  // Recursively iterate over all child nodes
  for (let i = 0; i < node.children.length; i++) { recursion(node.children[i], res); }}/ * * *@param {Node} root
 * @return {number[]}* /
var preorder = function (root) {
  let result = []; // Save the result

  // Recursively traverses the binary tree
  recursion(root, result);

  return result;
};
Copy the code