二叉树非递归遍历算法

二叉树非递归遍历算法

1. 前序遍历

    /**
     * 前序非递归遍历 借助链表和栈
     */
    @Override
    public void preOrderByStack() {
        System.out.print("前序非递归遍历:");
        if (root==null){
            System.out.println("二叉树为空!!!");
        }else {
            LinkedList<BinaryNode> list = new LinkedList<BinaryNode>();
            Queue<BinaryNode> stack = new LinkedList<>();
            BinaryNode current = root;
            while (current!=null || !stack.isEmpty()){
                while (current!=null){
                    list.add(current);
                    ((LinkedList<BinaryNode>) stack).push(current);
                    current = current.left;
                }
                if(!stack.isEmpty()){
                    current =((LinkedList<BinaryNode>) stack).pop();
                    current =current.right;
                }
            }

            for(BinaryNode binaryNode : list){
                System.out.print(binaryNode.value+" ");
            }
            System.out.println();
        }
    }

2. 中序遍历

    /**
     * 二叉树的中序遍历(非递归)   借助栈
     */
    @Override
    public void inOrderByStack() {
        System.out.print("中序非递归遍历:");
        //创建栈
        Deque<BinaryNode> stack = new LinkedList<BinaryNode>();
        BinaryNode current =root;
        while (current!=null || !stack.isEmpty()){
            while (current!=null){
                stack.push(current);
                current=current.left;
            }
            if(!stack.isEmpty()){
                current=stack.pop();
                System.out.print(current.value+" ");
                current=current.right;
            }
        }
        System.out.println();
    }

3. 后序遍历

    /**
     * 后序非递归遍历  借助栈与 队列
     */
    @Override
    public void postOrderByStack() {
        System.out.print("后序非递归遍历:");
        ArrayList<BinaryNode> list = new ArrayList<BinaryNode>();
        if(root!=null){
            Deque<BinaryNode> stack = new LinkedList<>();
            stack.push(root);
            while (!stack.isEmpty()){
                BinaryNode current = stack.pop();
                list.add(0,current);
                if(current.left!=null){
                    stack.push(current.left);
                }
                if(current.right!=null){
                    stack.push(current.right);
                }
            }
            Iterator<BinaryNode> iterator  = list.iterator();
            while (iterator.hasNext()){
                System.out.print(iterator.next().value+" ");
            }
            System.out.println();
        }
    }

你可能感兴趣的:(二叉树非递归遍历算法)