// 递归版本前序遍历public static void preOrder1(Node root){if(root == null){return ;}System.out.print( root.value+" ");preOrder1(root.left);preOrder1(root.right);}// 非递归版本前序遍历 头左右// 1)把头节点压入栈中,从栈中弹出一个节点cur// 2)打印cur// 3)先右再左入栈(如果有的话)// 4)重复操作public static void preOrder2(Node head){if(head == null){return;}Stack<Node> stack = new Stack<>();stack.add(head);while(!stack.isEmpty()){Node pop = stack.pop();System.out.print(pop.value + " ");if(pop.right != null){stack.push(pop.right);}if(pop.left != null){stack.push(pop.left);}}}// 归版本后序遍历 左右头public static void laterOrder1(Node head){if(head == null){return;}laterOrder1(head.left);laterOrder1(head.right);System.out.print(head.value+" ");}// 非递归版本后序遍历 左右头// 1)把头节点压入栈中,从栈中弹出一个节点cur,// 2)把cur放入收集栈中// 3)先左再右入栈(如果有的话)// 4)重复操作 收集完打印// 头左右→头右左→左右头public static void laterOrder2(Node head){if(head == null){return;}Stack<Node> stack1 = new Stack<>();Stack<Node> stack2 = new Stack<>();stack1.push(head);while(!stack1.isEmpty()){Node pop = stack1.pop();stack2.push(pop);if(pop.left != null){stack1.push(pop.left);}if(pop.right != null){stack1.push(pop.right);}}while(!stack2.isEmpty()){Node pop = stack2.pop();System.out.print(pop.value+" ");}}// 递归版本中序遍历 左头右public static void MidOrder1(Node head){if(head == null ){return;}MidOrder1(head.left);System.out.print(head.value + " ");MidOrder1(head.right);}// 非递归版本中序遍历 左头右// 每棵子树整棵树左边界进栈,依次弹出的过程中打印,对弹出节点的右树做重复操作压左边界进栈。// 左头右(分解)// 左头右....public static void MidOrder2(Node head){if(head == null ){return;}Stack<Node> stack = new Stack<>();while(!stack.isEmpty() || head != null){// 一直压左树,为空出栈打印,并对右树做同样操作。if(head != null){stack.push(head);head = head.left;}else {head = stack.pop();System.out.print(head.value + " ");head = head.right;}}}// 树的宽度遍历public static void WidthOrder(Node head){if(head == null){return;}Queue<Node> queue = new LinkedList<>();queue.add(head);while(!queue.isEmpty()){Node poll = queue.poll();System.out.print(poll.value + " ");if(poll.left != null){queue.add(poll.left);}if(poll.right != null){queue.add(poll.right);}}}
