0 课程地址
https://coding.imooc.com/lesson/207.html#mid=15183
1 重点关注
1.1 红黑树本节解析草图
1.2 红黑树新增节点草图解析
1.3 avl树和红黑树的使用场景
如果应用于查找,avl树更快一些,(见1.2)
如果应用于新增删除修改,红黑树更快一些(见13-10)
2 课程内容
3 Coding
3.1 红黑树部分关键代码
//1 定义Node class Node{ private K key; private V value; private Node left,right; private int height; private boolean color; public Node(K key, V value){ this.key = key; this.value = value; this.left = null; this.right = null; this.height = 1; this.color = RED; } @Override public String toString() { final StringBuffer sb = new StringBuffer("Node{"); sb.append("key=").append(key); sb.append(", value=").append(value); sb.append('}'); return sb.toString(); } } /** * 添加节点后根节点设置为黑色 * @author weidoudou * @date 2023/5/5 7:01 * @param key 请添加参数描述 * @param value 请添加参数描述 * @return void **/ public void add(K key, V value) { root = add(key,value,root); root.color = BLACK; } // node x // / \ 左旋转 / \ // T1 x ---------> node T3 // / \ / \ // T2 T3 T1 T2 private Node leftRotate(Node node) { Node x = node.right; Node T2 = x.left; // 向左旋转过程 node.right = T2; x.left = node; // 更新color x.color = node.color; node.color = RED; return x; }
诸葛