590. N 叉树的后序遍历

128 阅读1分钟

题目

image.png

image.png

思路

  • 正序压栈,结果头插

迭代

class Solution { 
    public List<Integer> postorder(Node root) {
        LinkedList<Integer> res = new LinkedList<>();
        if (root == null) return res;//特判
        Stack<Node> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            Node cur = stack.pop();
            res.addFirst(cur.val);//头插
            for (int i = 0; i < cur.children.size(); i++) {//正序压栈
                stack.push(cur.children.get(i));//由于这里是限制再size()内,所以不用担心加入null节点
            }
        }
        return res;
    }
}

递归

class Solution {
    List<Integer> res = new ArrayList<>();
    public List<Integer> postorder(Node root) {
        dfs(root);
        return res;
    }
    public void dfs(Node root) {
        if (root == null) {//这其实是特判
            return;
        }
        for (Node node : root.children) {
            dfs(node);
        }
        res.add(root.val);
    }
}