u
, v
, and w
be three nodes such that u
is in the left subtree of v
and w
is in the right subtree of v
.key(u) <= key(v) <= key(w)
O(logn)
stepsfind(7)
k
, we trace a downward path starting at the rootk
with the key of the current nodeAlgorithm 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())
find(4)
TreeSearch(4, root)
참고 : 티스토리 DEV_NUNU - 이진 검색 트리 2
Step 1) Find k
Step 2) Insert k
k
is not already in the tree, and let w
be the leaf reached by the searchk
at node w
and expand w
into an internal nodepublic:
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;
}
put(5,"A")
Inserting an entry with key 78
참고 : 티스토리 DEV_NUNU - 이진 검색 트리 3
erase(k)
, we search for key k
k
is in the tree, and let v
be the node storing k
v
has a leaf child w
, we remove v
and w
from the tree with operation removeAboveExternal(w)
, which removes w
and its parent
removeAboveExternal(w)
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
}
erase(4)
Removing an entry with key 32
k
to be removed is stored at a node v
whose children are both internal
w
that follows v
in an inorder traversalkey(w)
into node v
w
and its left child z
(which must be a leaf) by means of operation removeAboveExternal(z)
erase(3)
Removing an entry with key 65
h
is O(n)
in the worst casen
items implemented by means of a binary search tree of height h
find
, put
and erase
take O(h) = O(n)
timesize
, empty
take O(1)
v
of T
, the heights of the children of v
can differ by at most 1 (왼쪽, 오른쪽 서브 트리의 높이 차이가 최대 1 입니다.)n
keys is O(logn)
(a,b,c)
be an inorder listing of x
,y
,z
b
the topmost node of the threeVisualization : 2-3-4 tree (초기 로딩느림 주의)