“This is the first day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021”

[B] [C] [D]

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

Example 1:

Input: root = [1,null,2,3] output: [1, 3]Copy the code

Example 2:

Input: root = [] Output: []Copy the code

Example 3:

Input: root = [1] Output: [1]Copy the code

Example 4:

Input: root = [1,2] output: [2]Copy the code

Example 5:

Input: root = [1, NULL,2]Copy the code

In this case, we are going to do a forward traversal of the tree, that is, we are going to walk the whole binary tree from the left to the right of the roots

First open an empty array, and then iterate recursively from the root node

If the node is empty, the recursion is terminated. Otherwise, push the node values into the resulting array, recursively traversing the left and right subtrees

So that’s the answer to this question

The code is as follows:

var preorderTraversal = function(root) {
    const res = []
    function preorder(root){
        if(root === null) return;
        res.push(root.val);
        preorder(root.left);
        preorder(root.right);
    }
    preorder(root);
    return res;
};
Copy the code

At this point, we have completed the prior traversal of leetcode-144-binary tree

If you have any questions or suggestions, please leave a comment!