LeetCode.0590.叉树的后序遍历

版权声明:啦啦啦,不用于商业的话随便拿,记得带上博客地址http://blog.csdn.net/wjoker https://blog.csdn.net/wjoker/article/details/84207442

0590.N叉树的后序遍历

描述

给定一个 N 叉树,返回其节点值的后序遍历

实例

例如,给定一个 3叉树 :

返回其后序遍历: [5,6,3,2,4,1].

说明

递归法很简单,你可以使用迭代法完成此题吗?

题解

后序遍历N叉树和二叉树的方法可以相互参考

虽然是迭代难写…但是时间复杂度小的都是递归写法…

  • root为叶子结点➡️直接访问
  • root为非叶子节点
    • pre!=nullpre == root.children(last)相等,说明子节点已经都访问过了➡️直接访问
    • pre == root.children(last)说明子节点尚未访问,将其子节点由尾至首依次加入栈
    public List<Integer> postorder(Node root) {
        Node preNode = null;
        Stack<Node> stack = new Stack<>();
        List<Integer> result = new ArrayList<>();
        if (root == null)
            return result;

        stack.push(root);
        while (!stack.isEmpty()){
            root = stack.peek();
            if (root == null){
                stack.pop();
                continue;
            }

            //root为叶子结点,直接访问
            if ((root.children == null) || (root.children.size() == 0)){
                result.add(root.val);
                preNode = stack.pop();
                continue;
            }

            //root为非叶子节点且所有子节点已经被访问,直接访问
            if ((preNode != null) && (preNode == root.children.get(root.children.size()-1))){
                result.add(root.val);
                preNode = stack.pop();
                continue;
            }

            //root为非叶子节点,且子节点没有被访问过
            List<Node> children = root.children;
            for (int i = children.size()-1; i >= 0; i--) {
                stack.push(children.get(i));
            }
        }
        return result;
    }

猜你喜欢

转载自blog.csdn.net/wjoker/article/details/84207442
今日推荐