Antecedent traversal of binary trees

Give you the root node of the binary tree, root, and return a pre-traversal of the value of the node

The problem solving code

Idea: recursive, directly traverse the left and right subtrees, pass in the node value can be.

var preorderTraversal = function(root) {
  let ans = [];
  preOrder(root, ans); // Because the preceding traversal is around the root, it goes directly to the root node.
  return ans; // Return the result array
};
// Receive a binary tree and an array of results
var preOrder = function(root, ans) {
  if (root === null) return;
  ans.push(root.val); // Add the value of the loop to the array
  preOrder(root.left, ans); // Recursively traverse the left subtree
  preOrder(root.right, ans);// Recursively traverse the right subtree
}
Copy the code