589. N 叉树的前序遍历

广度优先遍历 BFS

解题思路

leetcode🧑‍💻 144. 二叉树的前序遍历

实现代码

var preorder = function (root) {
    const res = [];

    if (root === null) return res;
    const stack = [];
    stack.push(root);

    while (stack.length) {
        let len = stack.length;

        while (len) {
            const node = stack.pop();
            res.push(node.val);
            node.children.reverse().forEach(item => {
                stack.push(item);
            });
            len--;
        }
    }

    return res;
};

深度优先遍历 DFS

实现代码

var preorder = function (root) {
    const res = [];

    const dfs = (root) => {
        if (root === null) return;

        res.push(root.val);
        root.children.forEach(node=>{
            dfs(node);
        })
    };
    dfs(root);

    return res;
};
打赏作者
您的打赏是我前进的动力
微信
支付宝
评论

中午好👏🏻,我是 ✍🏻   疯狂 codding 中...

粽子

这有关于前端开发的技术文档和你分享。

相信你可以在这里找到对你有用的知识和教程。

了解更多

目录

  1. 1. 广度优先遍历 BFS
    1. 1.1. 解题思路
    2. 1.2. 实现代码
  2. 2. 深度优先遍历 DFS
    1. 2.1. 实现代码