0590. N Ary Tree Postorder Traversal

590. N-ary Tree Postorder Traversal #

题目 #

给定一个 n 叉树的根节点 root,返回其节点值的 后序遍历

思路 #

  • 递归
  • 迭代

代码 #

递归 #

class Node {
    public int val;
    public List<Node> children;
    
    public Node() {}
    public Node(int _val) { val = _val; }
    public Node(int _val, List<Node> _children) { val = _val; children = _children; }
}
class Solution {
    public void traversal(Node root, List<Integer> ans) {
        if (root == null) return;
        for (Node child: root.children) traversal(child, ans);
        ans.add(root.val);
    }
    public List<Integer> postorder(Node root) {
        List<Integer> ans = new LinkedList<>();
        traversal(root, ans);
        return ans;
    }
}

迭代 #