二叉树的三种递归遍历:
1 public class StudentNode 2 { 3 private String name; 4 5 private StudentNode leftNode; 6 7 private StudentNode rightNode; 8 9 public String getName() 10 { 11 return name; 12 } 13 14 public void setName(String name) 15 { 16 this.name = name; 17 } 18 19 public StudentNode getLeftNode() 20 { 21 return leftNode; 22 } 23 24 public void setLeftNode(StudentNode leftNode) 25 { 26 this.leftNode = leftNode; 27 } 28 29 public StudentNode getRightNode() 30 { 31 return rightNode; 32 } 33 34 public void setRightNode(StudentNode rightNode) 35 { 36 this.rightNode = rightNode; 37 } 38 39 public static void main(String[] args) 40 { 41 StudentNode root = new StudentNode(); 42 root.setName("Name1"); 43 StudentNode node2 = new StudentNode(); 44 node2.setName("Name2"); 45 StudentNode node3 = new StudentNode(); 46 node3.setName("Name3"); 47 StudentNode node4 = new StudentNode(); 48 node4.setName("Name4"); 49 StudentNode node5 = new StudentNode(); 50 node5.setName("Name5"); 51 StudentNode node6 = new StudentNode(); 52 node6.setName("Name6"); 53 StudentNode node7 = new StudentNode(); 54 node7.setName("Name7"); 55 // 56 // ****root*** 57 // ***/ **\*** 58 // **2 ****5** 59 // */ \ **/*** 60 // 3 *4 **6*** 61 // *******\*** 62 // ********7** 63 // 64 root.setLeftNode(node2); 65 root.setRightNode(node5); 66 node2.setLeftNode(node3); 67 node2.setRightNode(node4); 68 node5.setLeftNode(node6); 69 node6.setRightNode(node7); 70 71 // 前序遍历1-2-3-4-5-6-7 72 rootFirst(root); 73 // 中序遍历3-2-4-1-6-7-5 74 rootMiddle(root); 75 // 后序遍历3-4-2-7-6-5-1 76 rootLast(root); 77 } 78 79 private static void rootFirst(StudentNode node) 80 { 81 System.out.println(node.getName()); 82 if (null != node.getLeftNode()) 83 { 84 rootFirst(node.getLeftNode()); 85 } 86 if (null != node.getRightNode()) 87 { 88 rootFirst(node.getRightNode()); 89 } 90 } 91 92 private static void rootMiddle(StudentNode node) 93 { 94 if (null != node.getLeftNode()) 95 { 96 rootMiddle(node.getLeftNode()); 97 } 98 System.out.println(node.getName()); 99 if (null != node.getRightNode()) 100 { 101 rootMiddle(node.getRightNode()); 102 } 103 } 104 105 private static void rootLast(StudentNode node) 106 { 107 if (null != node.getLeftNode()) 108 { 109 rootLast(node.getLeftNode()); 110 } 111 if (null != node.getRightNode()) 112 { 113 rootLast(node.getRightNode()); 114 } 115 System.out.println(node.getName()); 116 } 117 }