LeetCode0145.二叉树的后序遍历

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

0145.二叉树的后序遍历

描述

给定一个二叉树,返回它的 后序 遍历。

实例

输入: [1,null,2,3]  
   1
    \
     2
    /
   3 

输出: [3,2,1]

进阶

递归算法很简单,你可以通过迭代算法完成吗?

题解

后序遍历时,有如下几种情况

  • root为叶子结点 ➡️直接访问
  • root为非叶子节点,但子节点未被访问 ➡️将root的右左孩子依次进栈
  • root为非叶子节点,且子节点未被访问 ➡️直接访问 该情况有以下可能
    • root有且只有左孩子,且左孩子为上一个访问的节点
    • root有右孩子,且右孩子为上一个访问的节点(实现是,由于pre初始化null有可能root.right == null == pre因此,需要加上条件为此时pre!= null
    public static List<Integer> postorderTraversal(TreeNode root) {
        TreeNode pre = null;
        Stack<TreeNode> 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.right == null && root.left == null){
                root = stack.pop();
                pre = root;
                result.add(root.val);
                continue;
            }

            //root为非叶子结点,但是子节点已经被访问过,直接访问
            //root只有左孩子且pre==root.left
            //或者root有右孩子且pre == root.right,此时pre不能等于null
            if (((root.right == null) && (pre == root.left)) || ((root.right == pre) && (pre != null))){
                root = stack.pop();
                pre = root;
                result.add(root.val);
                continue;
            }

            stack.push(root.right);
            stack.push(root.left);
        }
        return result;
    }

猜你喜欢

转载自blog.csdn.net/wjoker/article/details/84206732