leetcode
leetcode copied to clipboard
589. N叉树的前序遍历
给定一个 N 叉树,返回其节点值的前序遍历。
例如,给定一个 3叉树 :

返回其前序遍历: [1,3,5,6,2,4]。
说明: 递归法很简单,你可以使用迭代法完成此题吗?
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
- 递归遍历
const preorder = root => {
if (!root) return []
const res = [root.val]
const children = root.children || []
for (let i = 0; i < children.length; i++) {
res.push(...preorder(children[i]))
}
return res
}
- 迭代 = 栈 + 深度优先搜索
const preorder = root => {
if (!root) return []
const stack = [root], res = []
while (stack.length) {
const curr = stack.pop()
const children = curr.children || []
res.push(curr.val)
for (let i = children.length - 1; i >= 0; i--) {
stack.push(children[i])
}
}
return res
}