public class Node { private String node; private Node leftNode; private Node rigthNode; public Node(String node) { this.node = node; } public String getNode() { return node; } public void setNode(String node) { this.node = node; } public Node getLeftNode() { return leftNode; } public void setLeftNode(Node leftNode) { this.leftNode = leftNode; } public Node getRigthNode() { return rigthNode; } public void setRigthNode(Node rigthNode) { this.rigthNode = rigthNode; } } public class Test { private static Node root; private static StringBuffer sbuff = new StringBuffer(); public static void main(String[] args) { String[] nodes = new String[] { "12a", "jd", "33", "xa", "41d", "ddf", "ddfg", "ff11", "bb1", "21d" }; for (int i = 0; i < nodes.length; i++) { if (root == null) { root = new Node(nodes[i]); } else { makeBinaryTree(root, nodes[i]); } } moddleSort(root); System.out.println(sbuff.toString()); } /** * * 生成二叉树 * * * * @param prent * * 根节点 * * @param node * * 插入到该二叉树中的新节点 */ public static void makeBinaryTree(Node prent, String node) { Node newNode = new Node(node); if (prent.getNode().compareTo(node) > 0) { // left Node left = prent.getLeftNode(); if (null == left) { prent.setLeftNode(newNode); } else { makeBinaryTree(left, node); } } if (prent.getNode().compareTo(node) < 0) { // rigth Node rigth = prent.getRigthNode(); if (null == rigth) { prent.setRigthNode(newNode); } else { makeBinaryTree(rigth, node); } } } /** * * 中序遍历 * * * * @param current */ public static void moddleSort(Node current) { if (null != current) { moddleSort(current.getLeftNode()); sbuff.append(current.getNode() + " "); moddleSort(current.getRigthNode()); } } /** * * 前序遍历 * * * * @param current */ public static void preSort(Node current) { if (null != current) { sbuff.append(current.getNode() + " "); preSort(current.getLeftNode()); preSort(current.getRigthNode()); } } /** * * 后序遍历 * * * * @param current */ public static void afterSort(Node current) { if (null != current) { afterSort(current.getLeftNode()); afterSort(current.getRigthNode()); sbuff.append(current.getNode() + " "); } } }