给定一个 n 叉树的根节点 root ,返回 其节点值的 后序遍历 。
n 叉树 在输入中按层序遍历进行序列化表示,每组子节点由空值 null 分隔(请参见示例)
示例 1:
输入: root = [1,null,3,2,4,null,5,6]
输出: [5,6,3,2,4,1]
示例 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]
输出:[2,6,14,11,7,3,12,8,4,13,9,10,5,1]
题解 :
/**
* // Definition for a Node.
* function Node(val,children) {
* this.val = val;
* this.children = children;
* };
*/
/**
* @param {Node|null} root
* @return {number[]}
*/
// 方法一:递归
var postorder = function (root) {
const res = []
helper(root, res)
return res
};
const helper = (root, res) => {
if (root === null) {
return
}
for(let ca of root.children){
helper(ca,res)
}
res.push(root.val)
}
// 方法二:迭代
var postorder = function (root) {
const res = []
if (root === null) {
return res
}
const stack = [];
const visited = new Set();
stack.push(root);
while (stack.length) {
const node = stack[stack.length - 1];
/* 如果当前节点为叶子节点或者当前节点的子节点已经遍历过 */
// visited存储的是有孩子节点的节点,示例1中的1,3
if (node.children.length === 0 || visited.has(node)) {
stack.pop();
res.push(node.val);
continue;
}
for (let i = node.children.length - 1; i >= 0; --i) {
stack.push(node.children[i]);
}
visited.add(node);
}
return res;
};
来源:力扣(LeetCode)
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。