给定一个 N 叉树,返回其节点值的前序遍历。
题目链接: https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/
递归:
/**
* // Definition for a Node.
* function Node(val, children) {
* this.val = val;
* this.children = children;
* };
*/
/**
* @param {Node} root
* @return {number[]}
*/
var preorder = function(root) {
const result = [];
const pre = (root) => {
if (!root) return;
result.push(root.val)
root.children.forEach(child => pre(child))
}
pre(root)
return result
};
栈:
var preorder = function(root) {
const res = [], stack = [];
if (!root) return res
stack.push(root)
while(stack.length) {
root = stack.pop()
res.push(root.val)
// stack.push(...root.children.reverse())
while(root.children.length) stack.push(root.children.pop())
}
return res
};