1. import java.util.Arrays;
    2. /**
    3. * Demo class
    4. *
    5. * @author shier
    6. * @date 2021/3/27
    7. */
    8. @SuppressWarnings("all")
    9. class BinaryTree { //现在实现一个二叉树
    10. private class Node { //1.创建内部类保存节点数据
    11. private Comparable data; //2.保存的操作数据,因为必须是Comparable的子类,且需判断大小
    12. private Node left;//3.保存左边节点,左子树
    13. private Node right;//4.保存右边节点,右子树
    14. //5.初始化节点
    15. public Node(Comparable data) {
    16. this.data = data;
    17. }
    18. //8.内部类添加节点
    19. public void addNode(Node newNode) {
    20. if (this.data.compareTo(newNode.data) > 0) { //比当前节点大,放左边
    21. if (this.left == null) { //左节点为空,直接放到左节点
    22. this.left = newNode;
    23. } else { //左节点不为空,去左节点再进行判断
    24. this.left.addNode(newNode);
    25. }
    26. } else { //比当前节点小,放右边
    27. if (this.right == null) {
    28. this.right = newNode;
    29. } else {
    30. this.right.addNode(newNode);
    31. }
    32. }
    33. }
    34. //10.返回数据 依据左-中-右从小到大返回
    35. public void toArrayNode() {
    36. if (this.left != null) {//左节点有数据,进入左节点
    37. this.left.toArrayNode();
    38. }
    39. //如果左节点没有数据,将自身节点(中)添加到结果集中
    40. BinaryTree.this.retData[BinaryTree.this.foot++] = this.data;
    41. if (this.right != null) {//自身节点(中)添加到结果集中后,判断右节点有无数据,如果有就进入
    42. this.right.toArrayNode();
    43. }
    44. }
    45. }
    46. //-------------------------------------------//
    47. private Node root; //6.任何数据结构都要抓主一个根,
    48. private int count; //6.保存个数
    49. private int foot = 0; //6.脚标
    50. private Object[] retData;//6.返回数据
    51. public void add(Object data) { //7.添加节点(元素)方法
    52. if (data == null) {
    53. return;
    54. }
    55. Node newNode = new Node((Comparable) data);
    56. if (this.root == null) { //如果根节点还没有数据,保存到根节点
    57. this.root = newNode;
    58. } else { //根节点有数据,交给内部类分开
    59. this.root.addNode(newNode);
    60. }
    61. count++; //完成保存后 ++
    62. }
    63. //9.返回数据
    64. public Object[] toArray() {
    65. this.foot = 0; //脚标清0
    66. this.retData = new Object[this.count];
    67. this.root.toArrayNode();//10.从根节点进入,交给内部类
    68. return this.retData;
    69. }
    70. }
    71. public class 二叉树 {
    72. public static void main(String[] args) {
    73. BinaryTree bt = new BinaryTree();
    74. bt.add("G");
    75. bt.add("X");
    76. bt.add("C");
    77. bt.add("Z");
    78. bt.add("A");
    79. System.out.println(Arrays.toString(bt.toArray()));
    80. }
    81. }
    82. //输出:
    83. [A, C, G, X, Z]