LeetCode --- 590. N叉树的后序遍历

// Definition for a Node.
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;
    }
};
  • 解法1:递归

class Solution {
    LinkedList<Integer> list = new LinkedList<>();
    public List<Integer> postorder(Node root) {
        if (root == null) return list;
        helper(root);
        list.add(root.val);
        return list;
    }
    private void helper(Node root) {
        for (Node node : root.children) {
            helper(node);
            list.add(node.val);
        }
    }
}
  • 解法2:非递归

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

猜你喜欢

转载自blog.csdn.net/songzhuo1991/article/details/104196553
今日推荐