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<count;i++){ array[i] = in.nextInt(); } Node[] nodeArray = new Node[count + 1]; for(int i = 1;i<= count;i++) { nodeArray[i] = new Node(); nodeArray[i].setData(array[i-1]) ; } for(int i = 1;i<= count;i++) { if(2*i <= count) { nodeArray[i].setLeftChild(nodeArray[2 * i]); } if(2*i + 1 <= count) { nodeArray[i].setRightChild(nodeArray[2 * i + 1]); } } Node root = nodeArray[1]; firstVisitRecursion(root); firstVisit(root); System.out.println(); endVisit(root); levelVisit(root); } /** * 先序遍历 * @param root */ private static void firstVisit(Node root) { Stack<Node> 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<Node> stack = new Stack<>(); Stack<Integer> 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<Node> 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()); } } } }
二叉树的先序遍历、后续遍历、层次遍历(非递归算法 java实现)
最新推荐文章于 2021-04-18 22:42:37 发布