import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Stack;public class InorderTraversal {// 先序遍历// 递归实现/** public static void preTraversal(TreeNode root) {* if (root != null) {* System.out.println(root.val);* preTraversal(root.left);* preTraversal(root.right);* }* * }*/// while (node != null) {// res.add(node.val);// stack.push(node);// node = node.left;// }// node = stack.pop();// node = node.right;// }// return res;// }// 循环迭代实现public static void preTraversal(TreeNode root) {System.out.println("====先序遍历====");if (root == null) {return;}TreeNode curr = root;Deque<TreeNode> stack = new LinkedList<TreeNode>();while (curr != null || !stack.isEmpty()) {while (curr != null) {System.out.println(curr.val);stack.push(curr);curr = curr.left;}TreeNode top = stack.pop();curr = top.right;// curr = curr.right;}}// 中序遍历// 递归实现/** public static void inTraversal(TreeNode root) {* if (root != null) {* preTraversal(root.left);* System.out.println(root.val);* preTraversal(root.right);* }* * }*/// 循环迭代public static void inTraversal(TreeNode root) {System.out.println("====中序遍历====");if (root == null) {return;}TreeNode curr = root;Stack<TreeNode> stack = new Stack<>();while (curr != null || !stack.isEmpty()) {while (curr != null) {stack.push(curr);curr = curr.left;}TreeNode top = stack.pop();System.out.println(top.val);curr = top.right;}}// 后序遍历// 递归/** public static void afterTraversal(TreeNode root) {* if(root != null){* afterTraversal(root.left);* afterTraversal(root.right);* System.out.println(root.val);* }* }*/// 循环迭代public static void afterTraversal(TreeNode root) {System.out.println("====后序遍历====");if (root == null) {return;}TreeNode curr = root;TreeNode prev = null;// 双端队列Deque<TreeNode> stack = new LinkedList<TreeNode>();while (curr != null || !stack.isEmpty()) {while (curr != null) {stack.push(curr);curr = curr.left;}TreeNode top = stack.pop();if(top.right == null || top.right == prev){System.out.println(top.val);prev = top;curr = null;}else{stack.push(top);curr = top.right;}}}// 循环迭代public static void levelTraversal(TreeNode root) {System.out.println("====层次遍历====");if (root == null) {return;}Deque<TreeNode> queue = new LinkedList<TreeNode>();queue.offer(root);while (!queue.isEmpty()) {for(int i = 0; i< queue.size(); i++){TreeNode head = queue.poll();System.out.println(head.val);if(head.left != null){queue.add(head.left);}if(head.right != null){queue.add(head.right);}}}}public static void main(String[] args) {TreeNode root = new TreeNode(1);root.left = new TreeNode(5);root.left.left = new TreeNode(4);root.left.right = new TreeNode(6);root.right = new TreeNode(2);root.right.left = new TreeNode(3);preTraversal(root);inTraversal(root);// System.out.println("====后序遍历====");afterTraversal(root);// System.out.println("====层次遍历====");levelTraversal(root);}
}
先序遍历
1
5
4
6
2
3
中序遍历
4
5
6
1
3
2
后序遍历
4
6
5
3
2
1
层次遍历
1
5
2
4
6
3