0
点赞
收藏
分享

微信扫一扫

Leetcode 590:N叉树的后序遍历

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

n 叉树 在输入中按层序遍历进行序列化表示,每组子节点由空值 null 分隔(请参见示例)。

//后序遍历N叉树
    public static List<Integer> postorder(Node root) {
        List<Integer> result=new ArrayList<>();
        Stack<Node> stack =new Stack<>();
        if (root!=null) stack.push(root);

        while (!stack.empty()){
            Node node =stack.pop();   //取栈顶元素
            result.add(node.val);
            if(node.children==null) continue;
            for (int i=0;i<node.children.size();i++){
                stack.push(node.children.get(i));
            }
        }

        Collections.reverse(result);

        return result;
举报

相关推荐

0 条评论