- 写在前面:记录学习《恋上数据结构与算法》的过程。
- 课程链接地址:https://ke.qq.com/course/385223
目录
二叉搜索树的引入
二叉搜索树(Binary Search Tree)
BST 接口设计
节点
判断不能为空
根节点
添加根节点
添加节点
找到父节点
创建新节点,添加
定义比较接口,元素必须实现接口
- 某种类型元素进行实现
- BST中调用
- 如果换一种需求,如下方式,年龄小的认为在二叉树中为大的节点
- 上面把比较判定放在Person里,写死了,没法满足更加灵活的需求
改善比较方式,创建比较器
- 创建比较器接口
- 在BST构造函数中调用
- 根据需求创建具体的比较器
- 调用创建的比较器
兼容以上两种比较方法
- 添加不需要比较器的构造函数
- 在类中实现,使用官方的Compareable
- 使用官方的Comparator实现自定义比较器
- 使用自定义的比较器和类中默认提供的
或者使用匿名类
打印BST
- 工具:https://github.com/CoderMJLee/BinaryTrees
- 使用步骤
- 实现BinaryTreelnfo接口
- 调用打印API
- BinaryTrees.println(bst);
- 实现下面接口
public interface BinaryTreeInfo {
/**
* who is the root node
*/
Object root();
/**
* how to get the left child of the node
*/
Object left(Object node);
/**
* how to get the right child of the node
*/
Object right(Object node);
/**
* how to print the node
*/
Object string(Object node);
}
- 测试1,调用类提供的比较逻辑
- 测试2,传入比较器
- 测试3,随机数
- 重写toString打印Parent
推荐几个网站
http://btv.melezinek.cz/binary-search-tree.html
https://www.cs.usfca.edu/~galles/visualization/Algorithms.html
https://yangez.github.io/btree-js/
值相等处理(覆盖原节点)
- 重写Person类toString
- 测试