[路飞] leetcode589. N 叉树的前序遍历

Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情

一、题目描述

leetcode589. N 叉树的前序遍历

给定一个叉树的根节点  root ,返回 其节点值的 前序遍历 。

n 叉树 在输入中按层序遍历进行序列化表示,每组子节点由空值null分隔(请参见示例)。

示例 1:

image.png

输入: root = [1,null,3,2,4,null,5,6]
输出: [1,3,5,6,2,4]
复制代码

示例 2:

image.png

输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
输出:[1,2,3,6,7,11,14,4,8,12,5,9,13,10]
复制代码

提示:

  • 节点总数在范围 [0, 104]
  • 0 <= Node.val <= 104
  • n 叉树的高度小于或等于 1000

二、思路分析

递归

无需展开理解,利用递归函数的语意信息去进行程序设计。

  • root为空直接返回
  • root有值就push到输出结果数组中,然后遍历其孩子们递归处理

迭代

  • root判空
  • 用数组模拟栈stack
  • 最终输出结果用res表示
  • 开始先把根节点推入栈中,取出栈顶元素(也就是节点),将节点值push到res中,遍历其孩子们
  • 因为是前序遍历(根左右的顺序),栈只能去后入的元素(栈顶元素),所以遍历节点孩子们时注意倒着遍历

三、JavaScript代码

/**
 * // Definition for a Node.
 * function Node(val, children) {
 *    this.val = val;
 *    this.children = children;
 * };
 */

/**
 * @param {Node|null} root
 * @return {number[]}
 */

// 递归
function _preorder (root, ans) {
    if(root == null) return;
    ans.push(root.val);
    for(let x = 0; x < root.children.length; x++) {
        _preorder(root.children[x], ans)
    }
}
var preorder = function(root) {
    let ans = []
    _preorder(root, ans)
    return ans
};

// 迭代
var preorder = function(root) {
    const res = [];
    if (root == null) {
        return res;
    }

    const stack = [];
    stack.push(root);
    while (stack.length) {
        const node = stack.pop();
        res.push(node.val);
        for (let i = node.children.length - 1; i >= 0; --i) {
            stack.push(node.children[i]);
        }
    }
    return res;
};

复制代码

四、总结

猜你喜欢

转载自juejin.im/post/7076736078614855688