Leetcode-589-N叉树前序遍历

109 阅读1分钟

题目

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

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

进阶:递归法很简单,你可以使用迭代法完成此题吗?

题解

递归

/**
 * // Definition for a Node.
 * function Node(val, children) {
 *    this.val = val;
 *    this.children = children;
 * };
 */
​
/**
 * @param {Node|null} root
 * @return {number[]}
 */
let rs ;
var preorder = function(root) {
    if(!root){
        return []
    }
    rs = []
    deep(root);
    return rs 
};
​
function deep(root){
    rs.push(root.val)
    if(root.children.length){
        root.children.forEach(item => deep(item))
    }
}