25-映射(Map)

一、用红黑树实现映射

Map类接口

package com.weyan.map;

public interface Map<K, V> {
    int size();
    boolean isEmpty();
    void clear();
    V put(K key,V value);
    V get(K key);
    V remove(K key);
    boolean containsKey(K key);
    boolean containsValue(V value);
    //遍历
    void traversal(Visitor<K, V> visitor);
    
    public static abstract class Visitor<K, V> {
        boolean stop;
        public abstract boolean visit(K key,V value);
    }
}


TreeMap类

package com.weyan.map;

import java.util.Comparator;
import java.util.LinkedList;
import java.util.Queue;


@SuppressWarnings({"unchecked","unused"})
public class TreeMap<K, V> implements Map<K, V> {
    private static final boolean RED = false;
    private static final boolean BLACK = true;
    private int size;
    // 根节点
    private Node<K, V> root;
    private Comparator<K> comparator;

    // java 默认构造函数是无参数
    public TreeMap() {
        this(null);
    }

    public TreeMap(Comparator<K> comparator) {
        this.comparator = comparator;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {

        return size == 0;
    }

    @Override
    public void clear() {
        root = null;
        size = 0;
    }

    @Override
    public V put(K key, V value) {
        keyNotNullCheck(key);
        // 添加第一个节点
        if (root == null) {
            root = new Node<K, V>(key, value, null);
            size++;
            // 添加节点之后的处理
            afterPut(root);
            return null;
        }
        // 添加的不是第一个节点
        // 找到父节点
        Node<K, V> parent = root;
        Node<K, V> node = root;
        int cmp = 0;
        while (node != null) {
            parent = node;
            cmp = compare(key, node.key);
            if (cmp > 0) {
                node = node.right;
            } else if (cmp < 0) {
                node = node.left;
            } else {// 相等
                V oldValue = node.value;
                node.key = key;
                node.value = value;
                return oldValue;
            }
        }
        // 看看插入到父节点的哪个位置
        Node<K, V> newNode = new Node<K, V>(key, value, parent);
        ;
        if (cmp > 0) {
            parent.right = newNode;
        } else if (cmp < 0) {
            parent.left = newNode;
        }
        size++;

        // 添加节点之后的处理
        afterPut(newNode);
        return null;
    }

    @Override
    public V get(K key) {
        Node<K, V> node = node(key);
        return node != null ? node.value : null;
    }

    @Override
    public V remove(K key) {
        return remove(node(key));
    }

    @Override
    public boolean containsKey(K key) {
        return node(key) != null;
    }

    @Override
    public boolean containsValue(V value) {
        if(root == null) return false;
        Queue<Node<K, V>> queue = new LinkedList<>();
        queue.offer(root);
        
        while (!queue.isEmpty()) {
            Node<K, V> node = queue.poll();
            if (valEquals(value, node.value)) return true;
            if(node.left != null) return queue.offer(node.left);
            if(node.right != null) return queue.offer(node.right);
        }
        return false;
    }

    @Override
    public void traversal(Visitor<K, V> visitor) {
        if(visitor == null) return;
        traversal(root, visitor);
    }
    
    private void traversal(Node<K, V> node,Visitor<K, V> visitor) {
        if(node == null || visitor.stop) return;
        
        traversal(node.left, visitor);
        if(visitor.stop) return;
        visitor.visit(node.key, node.value);
        traversal(node.right, visitor);
    }
    
    private boolean valEquals(V v1,V v2) {
        return v1 == null ? v2 == null : v1.equals(v2);
    }

    // 根据key查找对应的节点
    private Node<K, V> node(K key) {
        Node<K, V> node = root;
        while (node != null) {
            int cmp = compare(key, node.key);
            if (cmp == 0) {
                return node;
            }
            if (cmp > 0) {
                node = node.right;
            } else {
                node = node.left;
            }
        }
        return null;
    }
    
    private V remove(Node<K, V> node) {
        if (node == null) {
            return null;
        }
        size--;
        V oldValue = node.value;
        // 度为2的节点
        if (node.hasTwoChildrenNode()) {
            // 找到后继节点
            Node<K, V> s = successor(node);
            // 用后继节点的值覆盖度为2的节点的值
            node.key = s.key;
            node.value = s.value;
            // 删除后继节点
            node = s;
        }
        // 删除node节点(node的度必然是1或0)
        Node<K, V> replacement = node.left != null ? node.left : node.right;
        if (replacement != null) {// node是度为1节点
            // 更改parent
            replacement.parent = node.parent;
            // 更改parent的left/right的指向
            if (node.parent == null) {// node是度为1的节点,并且是根节点
                root = replacement;
            } else if (node == node.parent.left) {
                node.parent.left = replacement;
            } else { // node == node.parent.right
                node.parent.right = replacement;
            }
            // node:删除的节点,删除之后的处理
            afterRemove(node, replacement);
        } else if (node.parent == null) {// node是叶子节点并且是根节点
            root = null;
            // node:删除的节点,删除之后的处理。
            afterRemove(node, null);
        } else {// node是叶子节点,但不是根节点
            if (node == node.parent.right) {
                node.parent.right = null;
            } else {// node == node.parent.left
                node.parent.left = null;
            }
            // node:删除的节点,删除之后的处理。
            afterRemove(node, null);
        }
        return oldValue;
    }

    // 判断一个节点是否为空
    private void keyNotNullCheck(K key) {
        if (key == null) {
            throw new IllegalArgumentException("key must not be null");
        }
    }

    private void afterPut(Node<K, V> node) {
        Node<K, V> parent = node.parent;
        // 添加的是根节点
        if (parent == null) {
            black(node);
            return;
        }
        // 如果父节点是黑色,直接返回
        if (isBlack(parent))
            return;
        // 叔父节点
        Node<K, V> uncle = parent.sibling();
        // 祖父节点
        Node<K, V> grand = parent.parent;
        if (isRed(uncle)) {// 叔父节点是红色
            black(uncle);
            black(parent);
            // 把祖父节点当做是新添加的节点,染成红色。
            red(grand);
            // 递归
            afterPut(grand);
            return;
        }
        // 叔父节点不是红色
        if (parent.isLeftChild()) {// L
            // grand染成红色
            red(grand);
            if (node.isLeftChild()) {// LL
                // parent染成黑色
                black(parent);
            } else {// LR
                // node 染成黑色
                black(node);
                // parent左旋转
                rotateLeft(parent);
            }
            // grand 右旋转
            rotateRight(grand);
        } else {// R
            // grand染成红色
            red(grand);
            if (node.isLeftChild()) {// RL
                // node 染成黑色
                black(node);
                // parent右旋转
                rotateRight(parent);
            } else {// RR
                // parent染成黑色
                black(parent);
            }
            // grand 左旋转
            rotateLeft(grand);
        }

    }

    // 比较两个节点,返回值==0代表e1和e2相等;返回值>0代表e1>e2;返回值<0代表e1<e2
    private int compare(K e1, K e2) {
        if (comparator != null) {
            return comparator.compare(e1, e2);
        }
        return ((Comparable<K>) e1).compareTo(e2);

    }

    /* 染色 */
    private Node<K, V> color(Node<K, V> node, boolean color) {
        if (node == null)
            return node;
        node.color = color;
        return node;
    }

    // 染红色
    private Node<K, V> red(Node<K, V> node) {
        return color(node, RED);
    }

    // 染红色
    private Node<K, V> black(Node<K, V> node) {
        return color(node, BLACK);
    }

    /* 判断颜色 */
    // 当前颜色
    private boolean colorOf(Node<K, V> node) {
        return node == null ? BLACK : node.color;
    }

    // 是否为红色
    private boolean isRed(Node<K, V> node) {
        return colorOf(node) == RED;
    }

    // 是否为红色
    private boolean isBlack(Node<K, V> node) {
        return colorOf(node) == BLACK;
    }

    // 左旋转
    private void rotateLeft(Node<K, V> grand) {
        Node<K, V> parent = grand.right;
        Node<K, V> child = parent.left;
        grand.right = child;
        parent.left = grand;

        // 更新parent/grand/child的parent和parent/grand的高度
        afterRotate(grand, parent, child);
    }

    // 右旋转
    private void rotateRight(Node<K, V> grand) {
        Node<K, V> parent = grand.left;
        Node<K, V> child = parent.right;
        grand.left = child;
        parent.right = grand;

        // 更新parent/grand/child的parent和parent/grand的高度
        afterRotate(grand, parent, child);
    }

    // 更新parent/grand/child的parent和parent/grand的高度
    private void afterRotate(Node<K, V> grand, Node<K, V> parent, Node<K, V> child) {
        // parent称为子树的根节点,更新parent的parent
        parent.parent = grand.parent;
        if (grand.isLeftChild()) {
            grand.parent.left = parent;
        } else if (grand.isRightChild()) {
            grand.parent.right = parent;
        } else {
            root = parent;
        }

        // 更新child的parent
        if (child != null) {
            child.parent = grand;
        }
        // 更新grand的parent
        grand.parent = parent;

    }

    private void afterRemove(Node<K, V> node, Node<K, V> replacement) {
        // 删除的节点是红色
        if (isRed(node))
            return;
        // 用于取代node的子节点是红色
        if (isRed(replacement)) {
            // 将替代的子节点染为黑色
            black(replacement);
            return;
        }
        // 删除的是根节点
        Node<K, V> parent = node.parent;
        if (parent == null)
            return;

        // 删除的是黑色叶子节点[下溢]
        // 判断被删除的node是左还是右(需要注意)
        boolean left = parent.left == null || node.isLeftChild();
        Node<K, V> sibling = left ? parent.right : parent.left;
        if (left) {// 被删除的节点在左边,兄弟节点在右边
            if (isRed(sibling)) {// 兄弟节点是红色
                black(sibling);
                red(parent);
                rotateLeft(parent);
                // 更换兄弟
                sibling = parent.right;
            }

            // 兄弟节点必然是黑色
            if (isBlack(sibling.left) && isBlack(sibling.right)) {
                // 兄弟节点没有一个红色子节点,父节点要向下跟兄弟节点合并
                boolean parentBlack = isBlack(parent);
                black(parent);
                red(sibling);
                if (parentBlack) {
                    afterRemove(parent, null);
                }
            } else {// 兄弟节点至少有一个红色子节点
                    // 兄弟节点的右边是黑色,兄弟要先旋转
                if (isBlack(sibling.right)) {
                    rotateRight(sibling);
                    sibling = parent.right;
                }
                color(sibling, colorOf(parent));
                black(sibling.right);
                black(parent);
                rotateLeft(parent);
            }
        } else {// 被删除的节点在右边,兄弟节点在左边
            if (isRed(sibling)) {// 兄弟节点是红色
                black(sibling);
                red(sibling);
                rotateRight(parent);
                // 更换兄弟
                sibling = parent.left;
            }

            // 兄弟节点必然是黑色
            if (isBlack(sibling.left) && isBlack(sibling.right)) {
                // 兄弟节点没有一个红色子节点,父节点要向下跟兄弟节点合并
                boolean parentBlack = isBlack(parent);
                black(parent);
                red(sibling);
                if (parentBlack) {
                    afterRemove(parent, null);
                }
            } else {// 兄弟节点至少有一个红色子节点
                    // 兄弟节点的左边是黑色,兄弟要先旋转
                if (isBlack(sibling.left)) {
                    rotateLeft(sibling);
                    sibling = parent.left;
                }
                color(sibling, colorOf(parent));
                black(sibling.left);
                black(parent);
                rotateRight(parent);
            }
        }
    }

    // 前驱节点
    private Node<K, V> predecessor(Node<K, V> node) {
        if (node == null)
            return null;
        // 前驱节点在左子树当中(left.right.right.........)
        Node<K, V> p = node.left;
        if (p != null) {
            while (p.right != null) {
                p = p.right;
            }
            return p;
        }
        // 从父节点、祖父节点当中去找前驱节点
        while (node.parent != null && node == node.parent.right) {
            node = node.parent;
        }
        // node.parent == null && node.left == null
        return node.parent;
    }

    // 后继节点
    private Node<K, V> successor(Node<K, V> node) {
        if (node == null)
            return null;
        // 前驱节点在左子树当中(right.left.left.........)
        Node<K, V> p = node.right;
        if (p != null) {
            while (p.left != null) {
                p = p.left;
            }
            return p;
        }
        // 从父节点、祖父节点当中去找前驱节点
        while (node.parent != null && node == node.parent.left) {
            node = node.parent;
        }
        // node.parent == null && node.right == null
        return node.parent;
    }

    private static class Node<K, V> {
        K key;
        V value;
        boolean color = RED;
        // 左子节点
        Node<K, V> left;
        // 右子节点
        Node<K, V> right;
        // 父节点
        Node<K, V> parent;

        // 构造函数
        public Node(K key, V value, Node<K, V> parent) {
            this.key = key;
            this.value = value;
            this.parent = parent;
        }

        // 是否是叶子节点
        public boolean isLeaf() {
            return left == null && right == null;
        }

        // 度为2节点
        public boolean hasTwoChildrenNode() {
            return left != null && right != null;
        }

        // 当前节点是否是父节点的左子节点
        public boolean isLeftChild() {
            return parent != null && this == parent.left;
        }

        // 当前节点是否是父节点的右子节点
        public boolean isRightChild() {
            return parent != null && this == parent.right;
        }

        // 兄弟节点
        public Node<K, V> sibling() {
            if (isLeftChild()) {
                return parent.right;
            }
            if (isRightChild()) {
                return parent.left;
            }
            return null;
        }

    }

}


Main

package com.weyan;

import com.weyan.file.FileInfo;
import com.weyan.file.Files;
import com.weyan.map.Map;
import com.weyan.map.Map.Visitor;
import com.weyan.map.TreeMap;

public class Main {

    static void testTreeMap() {
        Map<String, Integer> map = new TreeMap<String, Integer>();
        map.put("c", 3);
        map.put("a", 1);
        map.put("b", 2);
        map.put("a", 4);
        // 遍历
        map.traversal(new Visitor<String, Integer>() {
            public boolean visit(String key, Integer value) {
                System.out.println(key + "出现的个数:" + value);
                return false;
            }
        });
    }

    private static void test2() {
        FileInfo fileInfo = Files.read("/Users/xieweiyan/Desktop/weyan/数据结构和算法/学习代码/06-二叉搜索树/src/com/weyan/printer",
                new String[] { "java" });
        System.out.println("文件数量:" + fileInfo.getFiles());
        System.out.println("代码行数:" + fileInfo.getLines());
        String[] words = fileInfo.words();
        System.out.println("单词数量:" + words.length);

        Map<String, Integer> map = new TreeMap<String, Integer>();
        for (int i = 0; i < words.length; i++) {
            // 重复单词的个数
            Integer count = map.get(words[i]);
            count = (count == null) ? 1 : (count + 1);
            map.put(words[i], count);
        }
        // 遍历每一个单词
        map.traversal(new Visitor<String, Integer>() {
            public boolean visit(String key, Integer value) {
                System.out.println("key:" + key + "," + "value:" + value);
                return false;
            }
        });
    }

    public static void main(String[] args) {
        testTreeMap();
        test2();
    }

}

验证结果

注:
Map的所用key组合在一起,其实就是一个Set
因此,Set可以间接利用Map来内部实现

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,271评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,725评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,252评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,634评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,549评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,985评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,471评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,128评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,257评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,233评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,235评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,940评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,528评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,623评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,858评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,245评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,790评论 2 339

推荐阅读更多精彩内容