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 and continue to traverse all the nodes.
  4. In this recursion, the logic of the current node is to be processed, that is, the value of the current node is to be stored. Since it is backward traversal, the storage time is after traversal of left and right 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;
  }

  // Recursively iterate over all child nodes
  for (let i = 0; i < node.children.length; i++) {
    recursion(node.children[i], res);
  }

  // After traversal, that is, after traversing all child nodes, store the value of the current node
  res.push(node.val);
}
/ * * *@param {Node} root
 * @return {number[]}* /
var postorder = function (root) {
  let result = []; // Save the result

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

  return result;
};
Copy the code