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