Leetcode 590. N-ary Tree Postorder Traversal

题目链接

https://leetcode.com/problems/n-ary-tree-postorder-traversal/description/

题目描述

Given an n-ary tree, return the postorder traversal of its nodes' values.

Note: Recursive solution is trivial, could you do it iteratively?

题解

后序遍历的得到结果的顺序是 左->右->中,我们可以采用中右左的遍历方式,最后把数组取反就可以了。

代码


/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val,List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
    public List<Integer> postorder(Node root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) { return list; }
        Stack<Node> s = new Stack<>();
        s.push(root);
        Node pre = null;
        while (!s.isEmpty()) {
            Node node = s.pop();
            list.add(node.val);
            for (Node n : node.children) {
                s.push(n);
            }
        }
        Collections.reverse(list);
        return list;
    }
}

猜你喜欢

转载自www.cnblogs.com/xiagnming/p/9547395.html