Computer-Science

Search Trees

1. Binary Search Trees

스크린샷 2021-12-14 오후 4 36 09

Example: find(7)

스크린샷 2021-12-14 오후 5 00 52

스크린샷 2021-12-14 오후 5 04 25

Algorithm TreeSearch(k, u)
  if u.isExternal()
    return u

  if k < u.key()
    return TreeSearch(k, u.left())
  else if k = u.key()
    return u
  else // k > u.key()
    return TreeSearch(k, u.right())

Example: find(4)

Insertion

참고 : 티스토리 DEV_NUNU - 이진 검색 트리 2

Step 1) Find k
Step 2) Insert k

public:
    void insertItem(const Key& k, const Element& e) // insert (key, element)
        { inserter(k, e); }
protected:
    BTPosition inserter(const Key& k, const Element& e) { // insert utillity
        BTPosition p = finder(k, T.root()); // find insertion spot
        // 내부노드인 경우
        while (T.isInternal(p)) // key already exists?
            // look further
            p = finder(k, T.rightChild(p)); // leftChild로 해도 아무 상관 없음
        // 외부노드인 경우
        T.expandExternal(p); // add new node here
        setItem(p, BSTItem(k, e)); // store (key, element)
        return p;
    }

Example: Insertion

Removal

참고 : 티스토리 DEV_NUNU - 이진 검색 트리 3

public:
    // remove using key
    void removeElement(const Key& k) throw(NonexistentElementException) {
        BTPosition p = finder(k, T.root()); // find the node
        if (p.isNull()) // not found?
            throw NonexistentElementException("Remove nonexistent element");
        remover(p); // remove it
    }
protected:
    BTPosition remover(const BTPosition& r) { // remove utility
        BTPosition p;
        if (T.isExternal(T.leftChild(r))) // left is external?
            p = T.leftChild(r); // remove from left
        else if (T.isExternal(T.rightChild(r))) // right is external?
            p = T.rightChild(r); // remove from right
        else {
            p = T.rightChild(r); // p = replacement
            do
                p = T.leftChild(p); // ... right subtree
            while (T.isInternal(p));
            setItem(r, T.parent(p).element()); // copy parent(p) to r
        }
        return T.removeAboveExternal(p); // remove p and parent
    }

Example: Removal

Removal (cont.)

Example: Removal

Performance

스크린샷 2021-12-14 오후 6 50 59

2. AVL Trees

Insertion

Trinode Restructuring

3. Splay Trees

4. (2,4) Trees

스크린샷 2022-04-18 - ᅩ전 1 37 22