Title

#树#N叉树的后序遍历

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;
    }
};
*/

class Solution {
    public List<Integer> postorder(Node root) {
        List<Integer> l = new ArrayList<>();
        dfs(root,l);
        return l;
    }


    public void dfs(Node root,List list) {
        if(root == null) return;
        root.children.forEach( h -> {
            dfs(h,list);
        });
        list.add(root.val);
    }



}
class Solution {
    public List<Integer> postorder(Node root) {
        Deque<Node> stack = new LinkedList<>();
        if(root == null) return Collections.emptyList();
        stack.push(root);
        LinkedList<Integer> list  = new LinkedList<>();
        while(stack.isEmpty() == false ) {
            Node parent = stack.pop();
            parent.children.forEach(h -> {
                stack.push(h);
            });
            list.addFirst(parent.val);
        }
        return list;
    }


     









}

 

posted @ 2020-07-14 21:33  .geek  阅读(207)  评论(0编辑  收藏  举报