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

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 step is to traverse the binary tree, which requires a recursive function to continue through the left and right 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 a sequential traversal, the storage time is before traversal of left and right nodes.
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; *} * /
function recursion(node, res) {
  // If the node is empty, exit
  if(! node) {return;
  }

  // Preorder traversal, which prints the value of the current node before traversing the child nodes
  res.push(node.val);
  // Iterate over the left node
  recursion(node.left, res);
  // Iterate over the right node
  recursion(node.right, res);
}
/ * * *@param {TreeNode} root
 * @return {number[]}* /
var preorderTraversal = function (root) {
  let result = []; // Save the result
  // Recursively traverses the binary tree
  recursion(root, result);

  return result;
};
Copy the code