1 import java.util.LinkedList; 2 3 public class BinaryTreeErgodic { 4 5 /** 6 * 层次优先遍历 7 */ 8 public static void lavelOrderTraverse(TreeNode root) { 9 if (root == null) 10 return; 11 12 LinkedList<TreeNode> queue = new LinkedList<TreeNode>(); 13 TreeNode current = null; 14 queue.offer(root); 15 while (!queue.isEmpty()) { 16 current = queue.poll(); 17 System.out.print(current.value + " "); 18 if (current.left != null) 19 queue.offer(current.left); 20 if (current.right != null) 21 queue.offer(current.right); 22 } 23 } 24 25 /** 26 * 先序遍历 27 */ 28 public static void preOrderTraverse(TreeNode node) { 29 if (node == null) 30 return; 31 System.out.print(node.value + " "); 32 preOrderTraverse(node.left); 33 preOrderTraverse(node.right); 34 } 35 36 /** 37 * 中序遍历 38 */ 39 public static void inOrderTraverse(TreeNode node) { 40 if (node == null) 41 return; 42 inOrderTraverse(node.left); 43 System.out.print(node.value + " "); 44 inOrderTraverse(node.right); 45 } 46 47 /** 48 * 后序遍历 49 */ 50 public static void postOrderTraverse(TreeNode node) { 51 if (node == null) 52 return; 53 postOrderTraverse(node.left); 54 postOrderTraverse(node.right); 55 System.out.print(node.value + " "); 56 } 57 } 58 59 class TreeNode { 60 61 int value; 62 63 public TreeNode(int value) { 64 this.value = value; 65 } 66 67 TreeNode left = null; 68 TreeNode right = null; 69 }
上述代码分别实现了二叉树的:层次优先遍历、前序遍历(先序遍历)、中序遍历、后序遍历,具体原理大家都明白
原文:http://www.cnblogs.com/joshua-aw/p/6011794.html