后序遍历的非递归实现---利用栈

    //后续遍历的非递归实现
    public void postOrder(TreeNode root){
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode p = root;
        stack.push(p);
        TreeNode pre = null;
        
        while (!stack.isEmpty()) {
            TreeNode cur = stack.peek();
            if ((cur.left==null && cur.right==null) || (pre!=null && (pre==cur.left || pre==cur.right))) {
                System.out.println(cur.val);
                pre = stack.pop();
            }
            else{
                if (p.right!=null) {
                    stack.push(p.right);
                }
                if (p.left!=null) {
                    stack.push(p.left);
                }
                
            }
            
        }
        
        
        
    }

猜你喜欢

转载自blog.csdn.net/wwzheng16/article/details/81017677
今日推荐