美文网首页
2021-01-13

2021-01-13

作者: betterton | 来源:发表于2021-01-13 14:09 被阅读0次

递归前序遍历二叉树


/**

 * 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 array = [];

   digui(root);

    function digui(root) {

        if (root == null) return;

        // 根节点, 左子树, 右子树

        array.push(root.val);

        digui(root.left);

        digui(root.right);

    }

    return array;

};

相关文章

网友评论

      本文标题:2021-01-13

      本文链接:https://www.haomeiwen.com/subject/xsvuaktx.html