1. 题目
2. 思路
- 递归
- 迭代(借助栈的特性)
3. 代码实现
- 递归
/**
* // Definition for a Node.
* function Node(val, children) {
* this.val = val;
* this.children = children;
* };
*/
/**
* @param {Node|null} root
* @return {number[]}
*/
var preorder = function(root) {
// 递归
let res = []
if (root === null) return res
res.push(root.val)
if (root.children) {
root.children.forEach(item => {
res = [...res, ...preorder(item)]
})
}
return res
};
- 迭代
/**
* // Definition for a Node.
* function Node(val, children) {
* this.val = val;
* this.children = children;
* };
*/
/**
* @param {Node|null} root
* @return {number[]}
*/
var preorder = function(root) {
// 迭代(借用栈,后进先出)
let stack = [], res = []
if (root === null) return res
stack.push(root)
while (stack.length > 0) {
// 栈不为空
let node = stack.pop()
// console.log(node)
res.push(node.val)
if (node.children) {
node.children.reverse().forEach(item => {
// 栈是后进先出,因此要翻转一下node.children
stack.push(item)
})
}
// console.log(stack)
}
return res
};