Data Structure Java Edition Map&Set&Search Tree


Welcome  to visit ~

content

1. Search

1.1 Concept and Scenario

1.2 Model

2. Use of Map

2.1 Notes on Map

2.2 Description of Map.Entry,>

2.3 Description of common methods of Map

3. Description of Set

3.1 Description of common methods

4. Search tree

4.1 Concept

4.2 Search tree lookup

4.3 Insertion of the search tree

4.4 Deletion of the search tree


1. Search

1.1 Concept and Scenario

①The role of Map and Set:
A container or data structure specially used for searching, the efficiency of which is related to its specific instantiated subclass .
②The advantages of Map and Set compared to other types:
Common search methods we have learned before are:  direct traversal, binary search, etc.
The above sorting is more suitable for static type search, that is, the insertion and deletion operations are generally not performed on the interval, and the search in reality is such as:
1. Check test scores by name
2. The address book, that is, query the contact information according to the name
3. Do not repeat the set, that is, you need to search whether the keyword is already in the set
Some insertion and deletion operations may be performed during search, that is, dynamic search. The above two methods are not suitable. The Map and Set introduced in this section are collection containers suitable for dynamic search .

1.2 Model

1. Pure key model:

eg. There is an English dictionary to quickly find out whether a word is in the dictionary; to quickly find out whether a name is in the address book or not

2. Key-Value model :
eg. Count the number of occurrences of each word in the file. The statistical result is that each word has its corresponding number of times: <word, the number of occurrences of the word >; Liangshan hero's nickname: each hero has his own nickname
What is stored in Map is the key-value pair, and only the Key is stored in Set

2. Use of Map

2.1 Notes on Map

Map is an interface class that does not inherit from Collection . The key-value pair of the <K, V> structure is stored in this class , and K must be unique and cannot be repeated . (When repeated key values ​​appear in the future, the original value will be replaced)

The explanation diagram is as follows: (When repeated key values ​​appear in the future, the original value will be replaced)

2.2 Description of Map.Entry<K, V>

①Internal structure:

Map.Entry<K, V> is an internal class implemented by Map to store the mapping relationship of <key, value> key-value pairs . This internal class mainly provides the acquisition of <key, value>, the setting of value and the Key way of comparison.

( Consider <K, V> in Map.Entry<K, V> as a whole for storage )

② Commonly used methods
method explain
K getKey ()
Return the key in entry
V getValue ()
Returns the value in entry
V setValue(V value)
Replace the value in the key-value pair with the specified value

2.3 Description of common methods of Map

① Description of common methods:
method explain
V get(Object key) Returns the value corresponding to the key
V getOrDefault(Object key, V defaultValue) Return the value corresponding to the key , if the key does not exist, return the default value
V put(K key, V value) Set the value corresponding to the key
V remove(Object key) Delete the mapping relationship corresponding to the key
Set<K> keySet() Returns a unique set of all keys
Collection<V> values() Returns a repeatable collection of all values
Set<Map.Entry<K, V>> entrySet() Return all key-value mappings
boolean containsKey(Object key) Determine whether the key is included
boolean containsValue(Object value) Determine if it contains value

②The usage example is as follows: 

③Notes:

a. Map is an interface and cannot directly instantiate an object . If you want to instantiate an object, you can only instantiate its implementation class TreeMap or HashMap

b . The key that stores the key-value pair in the Map is unique, and the value can be repeated 

c. When inserting a key-value pair into a Map , the key cannot be empty, otherwise a NullPointerException will be thrown , but the value can be empty

The values ​​in d.Map can all be separated and stored in any sub-collection of Collection (values ​​may be repeated ).

e . The key of the key-value pair in the map cannot be modified directly, but the value can be modified. If you want to modify the key , you can only delete the key first , and then re-insert it.

3. Description of Set

There are two main differences between Set and Map : Set is an interface class inherited from Collection , and only Key is stored in Set

3.1 Description of common methods

① Description of common methods:
method explain
boolean add(E e) Add elements, but duplicate elements will not be added successfully
void clear() empty collection
boolean contains(Object o) Check if o is in the set
Iterator<E> iterator() return iterator
boolean remove(Object o) remove o from the set
int size()
Returns the number of elements in the set
boolean isEmpty() Check if the set is empty, return true if empty , otherwise return false
Object[] toArray() Convert the elements in the set to an array and return
boolean containsAll(Collection<?> c) Whether all the elements in the set c exist in the set, return true , otherwise return false
boolean addAll(Collection<? extends
E> c)
Adding the elements in the set c to the set can achieve the effect of deduplication

②The usage example is as follows: 

 ③Notes:

Only the key is stored in the Set, and the key must be unique (especially different from the Map)

4. Search tree

4.1 Concept

二叉搜索树又称二叉排序树,它或者是一棵空树,或者是具有以下性质的二叉树:

①如果它的左子树不为空,则左子树上所有节点的值都小于根节点的值

②如果它的右子树不为空,则右子树上所有节点的值都大于根节点的值

③它的左右子树也分别为二叉搜索树

4.2搜索树的查找

解题思路:

代码如下:

//创建结点
class Node {
    public int val;
    public Node left;
    public Node right;
    public Node(int val) {
        this.val = val;
    }
}

public class BinnarySearchTree {
    public Node root = null;
    public Node search(int value) {
        Node cur = root;
        while (cur != null) {
            if (cur.val < value) {
                cur = cur.right;
            } else if (cur.val == value) {
                return cur;
            } else {
                cur = cur.left;
            }
        }
        return null;//代表没有这个数据
    }

4.3搜索树的插入

解题思路:(与查找二叉树相似)

①查找到该根结点应该存储的位置

②存入该节点 

代码如下:

  public boolean insert(int val) {
        if (root == null) {
            root = new Node(val);
            return true;
        }

        Node cur = root;
        Node parent = null;
        while (cur != null) {
            if (cur.val < val) {
                parent = cur;
                cur = cur.right;
            } else if (cur.val == val) {
                return false;//不能有相同的数据
            } else {
                parent = cur;
                cur = cur.left;
            }
        }
        Node node = new Node(val);
        if (parent.val < val) {
            parent.right = node;
        } else {
            parent.left = node;
        }
        return true;
    }

4.4搜索树的删除(难点)

解题思路:

1. cur.left == null

①cur root ,则 root = cur.right
②cur 不是 root cur parent.left ,则 parent.left = cur.right
③cur 不是 root, cur parent.right ,则 parent.right = cur.right
2. cur.right == null
①cur root ,则 root = cur.left
②cur 不是 root cur parent.left ,则 parent.left = cur.left
③cur 不是 root cur parent.right ,则 parent.right = cur.left

 

3. cur.left != null && cur.right != null(难点)

思路: 需要使用 替换法 进行删除,即在它的右子树中寻找中序下的第一个结点 ( 关键码最小 ) ,用它的值填补到被删除节点中,再来处理该结点的删除问题

整体代码如下:

//创建节点
class Node {
    public int val;
    public Node left;
    public Node right;
    public Node(int val) {
        this.val = val;
    }
}
public void remove(int key) {
        Node cur = root;
        Node parent = null;
        while (cur != null) {
            if(cur.val == key) {
                //这里开始删除
                removeNode(cur,parent);
                break;
            }else if(cur.val < key) {
                parent = cur;
                cur = cur.right;
            }else {
                parent = cur;
                cur = cur.left;
            }
        }
    }

    public void removeNode(Node cur,Node parent) {
        if(cur.left == null) {
            if(cur == root) {
                root = cur.right;
            }else if(cur == parent.left) {
                parent.left = cur.right;
            }else {
                parent.right = cur.right;
            }
        }else if(cur.right == null) {
            if(cur == root) {
                root = cur.left;
            }else if(cur == parent.left) {
                parent.left = cur.left;
            }else {
                parent.right = cur.left;
            }
        }else {
            Node targetParent = cur;
            Node target = cur.right;
            while (target.left != null) {
                targetParent = target;
                target = target.left;
            }
            cur.val = target.val;
            if(target == targetParent.left) {
                targetParent.left = target.right;
            }else {
                targetParent.right = target.right;
            }
        }
    }
//中序遍历
    public void inOrder(Node root) {
        if(root == null) return;
        inOrder(root.left);
        System.out.print(root.val+" ");
        inOrder(root.right);
    }

 感谢观看~

Guess you like

Origin blog.csdn.net/weixin_58850105/article/details/123290752