[路飞]_144.二叉树的前序遍历

110 阅读1分钟

题目介绍

输入:root = [1,null,2,3] 输出:[1,2,3] 示例 2:

输入:root = [] 输出:[] 示例 3:

输入:root = [1] 输出:[1]

来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/bi… 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

递归法,递归遍历左右节点

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */

var preorderTraversal = function(root) {
    let arr = []
    function preorder(root) {
        if (!root) return
        arr.push(root.val)
        preorder(root.left)
        preorder(root.right)
    }
    preorder(root)
    return arr

};