给定一个 n 叉树的根节点 root ,返回 其节点值的 前序遍历 。
n 叉树 在输入中按层序遍历进行序列化表示,每组子节点由空值 null 分隔(请参见示例)。
示例 1:
输入: root = [1,null,3,2,4,null,5,6]
输出: [1,3,5,6,2,4]
示例 2:
输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
输出:[1,2,3,6,7,11,14,4,8,12,5,9,13,10]
题解:
/**
* // Definition for a Node.
* function Node(val, children) {
* this.val = val;
* this.children = children;
* };
*
/**
* @param {Node|null} root
* @return {number[]}
*/
// 方法一:递归
var preorder = function (root) {
const res = []
helper(root, res)
return res
};
const helper = (root, res) => {
if (root === null) {
return
}
res.push(root.val)
for (let ca of root.children) {
helper(ca, res)
}
}
// 方法二:迭代
var preorder = function (root) {
const res = [];
if (root === null) {
return res
}
const stack = []
// 前序遍历头节点进栈
stack.push(root)
while (stack.length) {
const node = stack.pop() // 获取当前节点
res.push(node.val)
// 从右至左遍历入栈。出栈时从左至右
for (let i = node.children.length - 1; i >= 0; --i){
stack.push(node.children[i])
}
}
return res
}
来源:力扣(LeetCode)
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。