class TreeNode { public int val; public TreeNode left; public TreeNode right; public TreeNode(int val) { this.val = val; } } public class BinaryTree { //先序遍历递归 public static void preOrder(TreeNode t) { if(t == null) { return; } System.out.print(t.val+" "); preOrder(t.left); preOrder(t.right); } //中序遍历递归 public static void inOrder(TreeNode t) { if(t == null) { return; } inOrder(t.left); System.out.print(t.val+" "); inOrder(t.right); } //后序遍历递归 public static void postOrder(TreeNode t) { if(t == null) { return; } postOrder(t.left); postOrder(t.right); System.out.print(t.val+" "); } //先序遍历非递归 public static void preOrder2(TreeNode t) { Stack<TreeNode> s = new Stack<>(); while(t!=null || !s.isEmpty()) { while(t != null)//遍历根节点和左子树 { System.out.print(t.val+" "); s.push(t); t = t.left; } if(!s.isEmpty())//遍历右孩子 { TreeNode temp = s.pop(); t = temp.right; } } } //中序遍历非递归 public static void inOrder2(TreeNode t) { Stack<TreeNode> s = new Stack<>(); while(t!=null || !s.isEmpty()) { while(t != null) { s.push(t); t = t.left; } if(!s.isEmpty()) { TreeNode temp = s.pop(); System.out.println(temp.val); t = temp.right; } } } //后序遍历非递归 public static void postOrder2(TreeNode t) { Stack<TreeNode> s = new Stack<>(); Stack<TreeNode> result = new Stack<>();//存储逆后序遍历结果 while(t != null || !s.isEmpty()) { while(t != null) { s.push(t); result.push(t); t = t.right; } if(!s.isEmpty()) { TreeNode temp = s.pop(); t = temp.left; } } while(!result.isEmpty()) { System.out.print(result.pop().val+" "); } } //层序遍历 public static void levelTraverse(TreeNode t) { ArrayDeque<TreeNode> queue = new ArrayDeque<>(); if(t == null) { return; } queue.offer(t); while(!queue.isEmpty()) { TreeNode temp = queue.poll(); System.out.print(temp.val + " "); if(temp.left != null) { queue.offer(temp.left); } if(temp.right != null) { queue.offer(temp.right); } } } //螺旋遍历 public static void spiralTraverse(TreeNode t) { Stack<TreeNode> s1 = new Stack<>(); Stack<TreeNode> s2 = new Stack<>(); if(t == null) { return; } s1.push(t); while(!s1.isEmpty() || !s2.isEmpty()) { while(!s1.isEmpty()) { TreeNode temp = s1.pop(); System.out.print(temp.val+" "); if(temp.right!=null) { s2.push(temp.right); } if(temp.left!=null) { s2.push(temp.left); } } while(!s2.isEmpty()) { TreeNode temp = s2.pop(); System.out.print(temp.val+" "); if(t.left!=null) { s1.push(temp.left); } if(temp.right!=null) { s1.push(temp.right); } } } } }