1 public class Demo { 2 public static void main(String[] args) { 3 MyTree t = new MyTree(); 4 t.add(12); 5 t.add(9); 6 t.add(5); 7 t.add(8); 8 t.add(11); 9 t.add(20); 10 t.zhongxu(); 11 } 12 } 13 class MyTree { 14 // 根节点 15 private Node root; 16 // 添加节点 17 public void add(int data) { 18 Node n = new Node(data); 19 // 如果根节点为空,则表明没有根节点,所以这个节点就为根节点 20 if (root == null) { 21 root = n; 22 } else { 23 // 如果根节点不为空,则调用节点的添加节点方法 24 this.root.add(n); 25 } 26 } 27 // 中序遍历 28 public void zhongxu() { 29 // 如果只有根节点,则return 30 if (root == null) { 31 return; 32 } 33 // 否则调用根节点的中序遍历 34 root.zhongxu(); 35 } 36 // 节点类 37 class Node { 38 // 数据 39 private int data; 40 // 左节点 41 private Node left; 42 // 右节点 43 private Node right; 44 // 构造方法,用于给Node进行赋值 45 public Node(int data) { 46 this.data = data; 47 } 48 // 中序遍历 49 public void zhongxu() { 50 // 判断左节点是否为空 51 if (this.left != null) { 52 // 如果左节点不为空,则继续调用左节点的中序遍历,递归调用 53 this.left.zhongxu(); 54 } 55 // 递归结束,输出数据 56 System.out.println(this.data); 57 // 判断右节点是否为空 58 if (this.right != null) { 59 // 如果右节点不为空,则继续调用右节点的中序遍历,递归调用 60 this.right.zhongxu(); 61 } 62 } 63 // 添加节点 64 public void add(Node n) { 65 // 判断要添加的数据比此节点的数据的大小,如果大,则添加在右子树,如果小,则添加在左子树 66 // 递归调用 67 if (n.data < this.data) { 68 if (this.left != null) { 69 this.left.add(n); 70 } else { 71 this.left = n; 72 } 73 } else { 74 if (this.right != null) { 75 this.right.add(n); 76 } else { 77 this.right = n; 78 } 79 } 80 } 81 } 82 }
执行结果:
1 5 2 8 3 9 4 11 5 12 6 20