【仅贴代码及测试结果】
-------------------BinaryTree.java------------------------------
class Tree{ E element; Tree lChild; Tree rChild; public Tree(E e){ element = e; }}public class BinaryTree { /** * 树形如下: * 1 * / \ * 2 3 * \ / \ * 4 5 6 */ public static void main(String[] args) { Tree n1 = new Tree (1); Tree n2 = new Tree (2); Tree n3 = new Tree (3); Tree n4 = new Tree (4); Tree n5 = new Tree (5); Tree n6 = new Tree (6); System.out.println("Construct the tree..."); n2.rChild=n4; n3.lChild=n5; n3.rChild=n6; n1.lChild=n2; n1.rChild=n3; System.out.println("打印先序遍历结果:"); firstOrder(n1); System.out.println("\n打印中序遍历结果:"); midOrder(n1); System.out.println("\n打印后序遍历结果:"); lastOrder(n1); } public static void firstOrder(Tree root){ if(root!=null){ System.out.print(root.element+" "); firstOrder(root.lChild); firstOrder(root.rChild); } } public static void lastOrder(Tree root){ if(root!=null){ lastOrder(root.lChild); lastOrder(root.rChild); System.out.print(root.element+" "); } } public static void midOrder(Tree root){ if(root!=null){ midOrder(root.lChild); System.out.print(root.element+" "); midOrder(root.rChild); } }}
输出结果:
Construct the tree...打印先序遍历结果:1 2 4 3 5 6 打印中序遍历结果:2 4 1 5 3 6 打印后序遍历结果:4 2 5 6 3 1