[leetcode] 590. N-ary Tree Postorder Traversal

题目:

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

For example, given a 3-ary tree:

Return its postorder traversal as: [5,6,3,2,4,1].

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

代码:

扫描二维码关注公众号,回复: 3120838 查看本文章
/*
// 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<Integer>();
        if(root == null) return list;
        for(Node children : root.children){
            list.addAll(postorder(children));
        }
        list.add(root.val);
        return list;
    }
}

猜你喜欢

转载自blog.csdn.net/jing16337305/article/details/82556537
今日推荐