Изменения

Перейти к: навигация, поиск

2-3 дерево

49 байт добавлено, 20:51, 11 мая 2015
Вставка элемента
'''function''' splitParent('''Node''' t):
'''if''' (t.length > 3)
Node a; a.sons[0] = t.sons[2] a.sons[1] = t.sons[3] t.sons[2].parent = a t.sons[3].parent = a a.keys[0] = t.keys[2] a.length = 2 t.length = 2 t.sons[2] = '''null''' t.sons[3] = '''null''' '''if''' (t.parent != '''null''') t.parent[t.length] = a t.length++ сортируем сыновей у t.parent splitParent(t.parent) '''else''' //мы расщепили корень, надо подвесить его к общему родителю, который будет новым корнем Node t = root root.sons[0] = t root.sons[1] = a t.parent = root a.parent = root root.length = 2 сортируем сыновей у root
Если сыновей стало <tex>3</tex>, то ничего не делаем. Далее необходимо восстановить ключи на пути от новой вершины до корня:
'''function''' updateKeys('''Node''' t):
Node a = t.parent
'''while''' (a != '''null''')
<tex>\mathtt{updateKeys}</tex> необходимо запускать от нового узла.
Добавление элемента:
'''function''' insert('''intT''' x): Node n = Node(x) '''if''' (root == null) root = n return Node a = search(x) '''if''' (a.parent == '''null''') Node t = root root.sons[0] = t root.sons[1] = n t.parent = root n.parent = root root.length = 2 сортируем сыновей у root '''else''' Node p = a.parent p.sons[p.length] = n p.length++ n.parent = p сортируем сыновей у p updateKeys(n) split(n)
updateKeys(n)
split(n)
updateKeys(n)
Так как мы спускаемся один раз, и поднимаемся вверх при расщеплении родителей не более одного раза, то <tex>\mathtt{insert}</tex> работает за <tex>O(\log{n})</tex>.
Анонимный участник

Навигация