| 一个数列 (7, 3, 10, 12, 5, 1, 9),要求能够高效的完成对数据的查询和添加 |
| |
| 数组未排序, 优点:直接在数组尾添加,速度快。 缺点:查找速度慢. |
| 数组排序,优点:可以使用二分查找,查找速度快,缺点:为了保证数组有序,在添加新数据时,找到插入位置后,后面的数据需整体移动,速度慢。 |
| 使用链式存储-链表不管链表是否有序,查找速度都慢,添加数据速度比数组快,不需要数据整体移动。 |
| 使用二叉排序树 |
| BST: (Binary Sort(Search) Tree), 对于二叉排序树的任何一个非叶子节点,要求左子节点的值比当前节点的值小,右子节点的值比当前节点的值大。 |
| 特别说明:如果有相同的值,可以将该节点放在左子节点或右子节点 |

| public class BinarySortTreeDemo { |
| |
| public static void main(String[] args) { |
| int[] arr = {7, 3, 10, 12, 5, 1, 9, 2}; |
| BinarySortTree binarySortTree = new BinarySortTree(); |
| |
| for(int i = 0; i< arr.length; i++) { |
| binarySortTree.add(new Node(arr[i])); |
| } |
| |
| |
| System.out.println("中序遍历二叉排序树~"); |
| binarySortTree.infixOrder(); |
| } |
| |
| } |
| |
| |
| class BinarySortTree { |
| private Node root; |
| |
| |
| public void add(Node node) { |
| if(root == null) { |
| root = node; |
| } else { |
| root.add(node); |
| } |
| } |
| |
| |
| public void infixOrder() { |
| if(root != null) { |
| root.infixOrder(); |
| } else { |
| System.out.println("二叉排序树为空,不能遍历"); |
| } |
| } |
| |
| } |
| |
| |
| class Node { |
| int value; |
| Node left; |
| Node right; |
| |
| public Node(int value) { |
| this.value = value; |
| } |
| |
| @Override |
| public String toString() { |
| return "Node [value=" + value + "]"; |
| } |
| |
| |
| |
| public void add(Node node) { |
| if(node == null) { |
| return; |
| } |
| |
| if(node.value < this.value) { |
| |
| if(this.left == null) { |
| this.left = node; |
| } else { |
| |
| this.left.add(node); |
| } |
| } else { |
| if(this.right == null) { |
| this.right = node; |
| } else { |
| |
| this.right.add(node); |
| } |
| } |
| } |
| |
| |
| public void infixOrder() { |
| if(this.left != null) { |
| this.left.infixOrder(); |
| } |
| System.out.println(this); |
| if(this.right != null) { |
| this.right.infixOrder(); |
| } |
| } |
| |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix