145. 二叉树的后序遍历

后序遍历和中序遍历大致相同,都是先要缓存前面的节点,直到最左孩子,此时pop出来的是二次访问的,但是后序的顺序是
三次访问是打印,所以给该节点加一个标注,先放置一个null,表示访问到null时,后一个节点就是第三那次方位了,直接打印即可。

    public List<Integer> postorderTraversal(TreeNode root) {
        // 创建栈,利用栈的倒序,实现最先处理最左边的节点,之后出栈,逐渐处理上一侧的节点
        Stack<TreeNode> stack = new Stack<>();
 
        List<Integer> ret = new ArrayList<>();
 
        // 尽量使用局部变量处理树结构
        TreeNode cur = root;
 
        while(cur != null || !stack.isEmpty()) {
            // 将该节点为起点,左孩子全部放入栈中
            
             while(cur!= null) {
                 stack.push(cur);
                 cur = cur.left;
             }
            
             cur = stack.pop();
             if(cur == null) {
                 ret.add(stack.pop().val);
             } else {
                 stack.push(cur);
                 stack.push(null);
                 // 出栈,处理节点的右孩子。之后右孩子做上述同样的逻辑。
                 cur = cur.right;
             }
            
        }
        
        return ret;  
    }

应用多叉树的遍历思路:590. N 叉树的后序遍历

    public List<Integer> postorderTraversal(TreeNode root) {
        if( root == null) {
            return new ArrayList<>();
        }

        List<Integer> ret = new ArrayList<>();

        Stack<TreeNode> stack = new Stack<>();

        TreeNode cur = root;
        stack.push(cur);

        while(!stack.isEmpty()) {
            cur = stack.pop();
            if(cur != null) {

                stack.push(cur);
                stack.push(null);

                if(cur.right != null) {
                    stack.push(cur.right);
                }

                if(cur.left != null) {
                    stack.push(cur.left);
                }


            } else {
                cur = stack.pop();
                ret.add(cur.val);
            }
        }
        return ret;
    }
posted @ 2022-02-22 22:39  一颗青菜  阅读(4)  评论(0)    收藏  举报