来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/n-ary-tree-postorder-traversal 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

给定一个 n 叉树的根节点 root ,返回 其节点值的 后序遍历 。 n 叉树 在输入中按层序遍历进行序列化表示,每组子节点由空值 null 分隔(请参见示例)。

解答

无论是 N 叉树还是二叉树,后续遍历的顺序都是左右中

  1. /**
  2. * // Definition for a Node.
  3. * function Node(val,children) {
  4. * this.val = val;
  5. * this.children = children;
  6. * };
  7. */
  8. /**
  9. * @param {Node|null} root
  10. * @return {number[]}
  11. */
  12. var postorder = function(root) {
  13. const ret = [];
  14. function traverse (node) {
  15. if (!node) return;
  16. node.children && node.children.forEach(child => traverse(child));
  17. ret.push(node.val);
  18. }
  19. traverse(root);
  20. return ret;
  21. };