二叉树的先序遍历、后续遍历、层次遍历(非递归算法 java实现)

import java.util.Scanner;
import java.util.Stack;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;


/**
 *              1
 *
 *           2        3
 *
 *       4      5    6    7
 *
 *     先序遍历  1  2  4 5  3  6  7
 *
 *     输入  :
 *     7
 *     1 2 3 4 5 6 7
 *
 *
 */
public class Hello {

    public static void main(String[] args)
    {

        Scanner in = new Scanner(System.in);
        int count  = in.nextInt();
        int[] array = new int[count];
        for(int i = 0;i  stack = new Stack<>();
        Node p = root;
        int top = -1;
        while(p != null || top != -1)
        {
            while(p != null)
            {
                System.out.print(p.getData() + " ");
                stack.push(p);
                top ++;
                p = p.getLeftChild();
            }
            p = stack.pop();
            top --;
            p = p.getRightChild();
        }


    }

    /**
     *  先序遍历--递归
     * @param root
     */
    private static void firstVisitRecursion(Node root)
    {
        if(root != null) {
            System.out.println(root.getData());
            firstVisitRecursion(root.getLeftChild());
            firstVisitRecursion(root.getRightChild());
        }


    }

    /**
     * 后序遍历
     * @param root
     */
    private static void endVisit(Node root)
    {
        Stack  stack = new Stack<>();
        Stack  stack2 = new Stack<>();
        Node p = root;
        int top = -1;
        while(p != null || top != -1)
        {
            while(p != null)
            {
                stack.push(p);
                stack2.push(0);
                top ++;
                p = p.getLeftChild();
            }
            p = stack.pop();
            top --;
            int result = stack2.pop();
            if(result == 0)
            {
                stack.push(p);
                stack2.push(1);
                top ++;
                p = p.getRightChild();
            }else
            {
                System.out.print(p.getData() + " ");
                p = null;
            }
        }


    }

    /**
     * 按照层次访问
     * @param root
     */
    private static void levelVisit(Node root)
    {
        System.out.println();
        BlockingQueue queue = new LinkedBlockingQueue<>();
        Node p = root;
        queue.offer(p);
        while(true)
        {
            Node temp = queue.poll();
            if(temp == null) {
                break;
            }
            System.out.print(temp.getData() + " ");
            if(temp.getLeftChild() != null) {
                queue.add(temp.getLeftChild());
            }
            if(temp.getRightChild() != null) {
                queue.add(temp.getRightChild());
            }
        }


    }





}

你可能感兴趣的:(Algorithm)