LeetCode第590题:N叉树的后序遍历

LeetCode第590题

题目详述

给定一个 N 叉树,返回其节点值的后序遍历。

解法一

递归。时间复杂度:O(n),空间复杂度O(logn)

class Solution {
    public List<Integer> postorder(Node root) {
        List<Integer> ans = new ArrayList<>();
        helper(root, ans);
        return ans;
    }
    public void helper(Node root, List ans) {
        if (root == null) return;
        int s = root.children.size();
        for (int i = 0; i < s; i++) helper(root.children.get(i), ans);
        ans.add(root.val);
    }
}

解法二

迭代。时间复杂度:O(n),空间复杂度:O(n)

class Solution {
    public List<Integer> postorder(Node root) {
        if (root == null) return new ArrayList();
        Stack<Node> stack = new Stack<>();
        LinkedList<Integer> list = new LinkedList<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            Node node = stack.pop();
            list.addFirst(node.val);
            for (Node temp : node.children) 
                if (temp != null) stack.push(temp);
        }
        return list;
    }
}
发布了40 篇原创文章 · 获赞 0 · 访问量 642

猜你喜欢

转载自blog.csdn.net/weixin_42610002/article/details/104377705