Изменения

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

Левосторонние красно-чёрные деревья

4518 байт добавлено, 19:08, 4 сентября 2022
м
rollbackEdits.php mass rollback
{{Определение
|definition = LeftЛевостороннее красно-leaning Red-Black Trees черное дерево {{---}} модификация [[Красно-черное дерево|тип сбалансированного двоичного дерева поиска, гарантирующий такую же асимптотическую сложность операций, как у красно-черных деревьев]], имеющая ряд преимуществ на классической структурой. Разработана Робертом Соджевиском в 2008 годучерного дерева поиска.
}}
 ==ПреимуществаСвойства==* необходимо менее 80 строчек кода для реализации структуры Корневой узел всегда черный.* более быстрая вставка, удаление элементовКаждый новый узел всегда окрашен в красный цвет.* простотаКаждый дочерний нулевой узел листа дерева считается черным. 
==Вращения==
Чтобы поддерживать левосторонние красно-черные двоичное двоичные деревья поиска необходимо соблюдать следующие инвариантные свойства инварианты при вставке и удалении:* Ни один обход путь от корня до листьев дерева не содержит двух последовательных красных узлов.
* Количество черных узлов на каждом таком пути одинаково.
Из этих инвариантов следует, что длина каждого пути от корня до листьев в красно-черном дереве с <tex>N</tex> узлами не превышает <tex>2 \cdot log(N)</tex> .
Основные операции, используемые алгоритмами сбалансированного дерева для поддержания баланса при вставке и удалении, называются вращениямивращением вправо и вращением влево. Эти операции Первая операция трансформируют <tex>3</tex>-узел(совокупность из <tex>3</tex> узлов, где <tex>2</tex> узла являются наследниками третьего, причем одна из связей является красной),левый потомок которого окрашен в красный, в <tex>3</tex>-узел, правый потомок которого окрашен в красный и ,вторая операция {{---}} наоборот. Вращения сохраняют два указанных выше инварианта, не изменяют поддеревья узла.===ПсевокодПсевдокод===
[[File:rotateRight.png|310px|thumb|upright|Rotate Right]]
'''Node''' rotateRight( h : '''Node''') :
x = h.left
h.left= x.right x.right= h
x.color = h.color
h.color = RED
'''return''' x
[[File:rotateLeft.png|310px|thumb|upright|Rotate Left]]
'''Node''' rotateLeft( h : '''Node''') :
x = h.right
h.right = x.left
x.color = h.color
h.color = RED
'''return''' x
==Переворот цветов==
 В красно-черных деревьях используется такая операция как <tex>color flip</tex>'''переворот цветов''' , которая инвертирует цвет узла и двух его детей. Она не изменяет количество черных узлов при на любом обходе пути от корня до листьев деревалиста, но может привести к появлению двух последовательных красных узлов. ===Псевдокод===[[File: ColorFlip.png|320px|thumb|upright| Color FlipПереворот цветов]]  '''void''' flipColors( h : '''Node''' h) :
h.color = '''!''' h.color
h.left.color = '''!''' h.left.color h.right.color = <tex> '''!</tex> ''' h.right.color
==Вставка==
Вставка в ЛСКЧД базируется на <tex>4</tex> простых операциях:
==Методы==*Вставка нового узла к листу дерева:Если высота узла нулевая, возвращаем новый красный узел.[[File:insertNode.png|310px|thumb|upright|Вставка нового узла]]*Расщепление узла с <tex>4</tex>-я потомками:Если левый предок и правый предок красные, запускаем переворот цветов от текущего узла.[[File:Split4node.png|310px|thumb|upright|Расщепление узла]]*Принудительное вращение влево:[[File:Enforce.png|310px|thumb|upright|Принудительное вращение]]Если правый предок красный, вращаем текущую вершину влево.*Балансировка узла с <tex>4</tex>-я потомками:[[File:Balance4node.png|310px|thumb|Балансировка]]Если левый предок красный и левый предок левого предка красный, то вращаем текущую вершину вправо.
===Псевдокод=== '''void''' insert( key : '''keyKey''' , value : Key, '''valueValue''' : Value ):
root = insert(root, key, value)
root.color = BLACK
'''Node''' insert( h : '''Node''', key : '''Key''', value : '''Value''') <span style="color:#008000">// Вставка нового листа</span> '''if''' h == ''null''
'''return''' '''new''' Node(key, value)
<span style="color:#008000">// Расщепление узла с <tex>4</tex>-я потомками</span> '''if''' isRed(h.left) '''&&''' isRed(h.right) colorFlip(h) <span style="color:#008000">// Стандартная вставка [[Дерево поиска, наивная реализация|в дереве поиска]]</span> '''intif''' cmp key = h.key.compareTo( h.key) val = value '''else''' '''if''' key < h.key cmp == 0 h.val left = insert(h.left, key, value)
'''else'''
'''if''' cmp < 0
h.left = insert(h.left, key, value)
'''else'''
h.right = insert(h.right, key, value)
<span style="color:#008000">// Принудительное вращение влево</span> '''if''' isRed(h.right) '''&&''' '''!'''isRed(h.left) h = rotateLeft(h) <span style="color:#008000">// Балансировка узла с <tex>4</tex>-я потомками</span>
'''if''' isRed(h.left) '''&&''' isRed(h.left.left)
h = rotateRight(h) '''return''' ''h''
==Поиск==
Поиск в левосторонних красно-черных деревьях эквивалентен поиску в [[Дерево поиска, наивная реализация|наивной реализации дерева поиска]].
Для поиска элемента в красно-черных деревьях дереве поиска можно воспользоваться циклом,который проходит от корня до искомого элемента. Если же элемент отсутствует, цикл пройдет до листа дерева и прервется. Для каждого узла цикл сравнивает значение его ключа с искомым ключом. Если ключи одинаковы, то функция возвращает текущий узел, в противном случае цикл повторяет для левого или правого поддерева. Узлы, которые посещает функция образуют нисходящий путь от корня, так что время ее работы <tex>O(h)</tex>, где <tex>h</tex> {{---}} высота дерева.
===Псевдокод===
'''Value''' search(key : '''Key''')
'''Node''' x = root
'''while''' (x '''!'''= null)
'''if''' key = x.key
'''return''' x.val
'''else'''
'''if''' key < x.key
x = x.left
'''else'''
'''if''' key > x.key
x = x.right
'''return''' ''null''
==Исправление правых красных связей==*Использование Переворота цветов и вращений сохраняет баланс черной связи.*После удаления необходимо исправить правые красные связи и устранить узлы с <tex>4</tex>-я потомками <span style="color:#008000">// Исправление правых красных связей</span> '''ValueNode''' searchfixUp(key h : '''KeyNode'''): '''Nodeif''' x isRed(h.right) h = rootrotateLeft(h) '''while''' x '''!''' <span style= null"color:#008000">// Вращение <tex>2</tex>-ой красной пары пары</span> '''intif''' cmp = key.compareToisRed(xh.keyleft) '''if&&''' cmp isRed(h.left.left) h =rotateRight(h) <span style= 0"color:#008000">// Балансировка узла с <tex>4</tex>-я потомками</span> '''return''' x.val '''else''' '''if''' cmp < 0 x = xisRed(h.left ) '''else&&''' '''if''' cmp > 0 x = xisRed(h.right) colorFlip(h) '''return''' ''null''h
==Удаление максимума==
* Спускаемся вниз по правому краю дерева.
* Если поиск заканчивается на узле с <tex>4</tex>-мя или <tex>5</tex>-ю потомками, просто удаляем узел.
==Удаление==f cient implementation of the delete operation is a challenge in many symbol-table implementa- tions, and red-black trees are no exception. Industrial[[File:34-strength implementations run to over 100 lines of code, and text books generally describe the operation in terms of detailed case studies, eschewing full implementationsnodeRemove. Guibas and Sedgewick presented a delete implementation in [7png|310px|thumb|center| Узлы до и после удаления], but it is not fully speci ed and depends on a call-by-reference approach not commonly found in modern code. The most popular method in common use is based on a parent pointers (see [6]), which adds substantial overhead and does not reduce the number of cases to be handled.The code on the next page is a full implementation of * Удаление узла с <tex>delete()</tex> for LLRB 2-3 trees. It is based on the reverse of the approach used for insert in top-down 2-3-4 trees: we perform rotations and color ips on the way down the search path to ensure that the search does not end on a 2-node, so that we can just delete the node at the bottom. We use the method <tex>fixUp()</tex> to share the code for the color ip and rotations following therecursive calls in the <tex>insert()</tex> code.With <tex>fixUp()</tex>, we can leave right-leaning red links and unbalanced 4-nodes along the search path, secureя потомками нарушает балансthat these conditions will be xed on the way up the tree. (The approach is also effective 2-3-4 treesСоответственно, but requires an extra rotation when the right nodeoff the search path is a 4-node.)As a warmup, consider the delete-the-minimum operation, where the goal is to delete the bottom node on the left spine while maintaining balance. To do so, we maintain the invariant that the current node or its left child is red. We can do so by moving to the left unless the current node is red and its left child and left grandchild are both black. In that case, we can do a color ip, which restores the invariant but may introduce successive reds on the right. In that case, we can correct the condition with two rotations and a color ip. These operations are implemented in the спускаясь вниз по дереву необходимо поддерживать следующий инвариант : количество потомков узла не должно быть ровно <tex>moveRedLeft()2</tex> method on the next page. With <tex>moveRedLeft()</tex>, the recursive implementation of <tex>deleteMin()</tex> above is straightforward.For general deletion, we also need <tex>moveRedRight()</tex>, which is similar, but simpler, and we need to rotate left-leaning red links to the right on the search path to maintain the invariant[[File:changeNode. If the node to be deleted is an internal node, we replace its key and value elds with those in the minimum node in its right subtree and then delete the minimum in the right subtree (or we could rearrange pointers to use the node instead of copying elds). The full implementation of <tex>delete()</tex> that dervies from this discussion is given on the facing page. It uses one-third to one-quarter the amount of code found in typical implementations. It has been demonstrated before [2, 11, 13png|600px|thumb|center| ]] that maintaining a eld in each node containing its height can lead to code for delete that is similarly concise, but that extra space is a high price to pay in a practical implementation. With <tex>LLRB</tex> trees, we can arrange for concise code having a logarithmic performance guarantee and using no extra space.
Будем поддерживать инвариант: для любого узла либо сам узел, либо правый предок узла '''красный'''.
Будем придерживаться тактики , что удалять лист легче, чем внутренний узел.
'''void''' deleteMin()Заметим, что если правый потомок вершины и правый потомок правого потомка вершины черные, необходимо переместить левую красную ссылку вправо для сохранения инварианта. root = deleteMin(root); root[[File:MinEasy.png|400px|thumb|right| Перемещение красной ссылки.color = BLACK;Простой случай]]
'''Node''' deleteMin(h [[File: '''Node''') if (hMinHard.left == ''null'') '''return''' ''null''; '''if !'''isRed(hpng|400px|thumb|right| Перемещение красной ссылки.left) '''&& !'''isRed(h.left.left) h = moveRedLeft(h); h.left = deleteMin(h.left); '''return''' fixUp(h);Сложный случай]]
Delete-the-minimum code for LLRB 2-3 trees===Псевдокод=== '''void''' deleteMax() root = deleteMax(root) root.color = BLACK
'''voidNode''' deleteMinmoveRedLeft(h : '''Node''') colorFlip(h): '''if''' isRed(h.right.left root h.right = deleteMinrotateRight(rooth.right) root.color h = BLACKrotateLeft(h) colorFlip(h) '''return''' h
'''Node''' deleteMax(h : '''Node''')
'''if''' isRed(h.left)
<span style="color:#008000">// вращаем все 3-вершины вправо</span>
h = rotateRight(h)
<span style="color:#008000">// поддерживаем инвариант (h должен быть красным)</span>
'''if''' h.right == ''null''
return ''null''
<span style="color:#008000">// заимствуем у брата если необходимо</span>
'''if''' !isRed(h.right) '''&&''' !isRed(h.right.left)
h = moveRedRight(h)
<span style="color:#008000">// опускаемся на один уровень глубже </span>
h.left = deleteMax(h.left)
<span style="color:#008000">// исправление правых красных ссылок и 4-вершин на пути вверх</span>
'''return''' fixUp(h)
'''Node''' deleteMin( h : '''Node'''): '''if''' h.left == ''null'' '''return''' ''null'' '''if''' !isRed(h.left) '''&&''' !isRed(h.left.left) h Удаление минимума== moveRedLeft(h) hПоддерживаем инвариант: вершина или левый ребенок вершины красный.left = deleteMin(h.left) '''return''' fixUp(h)
Заметим, что если левый потомок вершины и левый потомок левого потомка вершины черные, необходимо переместить красную ссылку для сохранения инварианта.
[[File:MoveRedLeftEasy.png.png |400px|thumb|upright|Перемещение красной ссылки. Простой случай]]
[[File:MoveRedLeftNoEasy.png|400px|thumb|upright|Перемещение красной ссылки. Сложный случай]]
===Псевдокод===
'''Node''' moveRedLeft(h : '''Node''')
colorFlip(h)
if isRed(h.right.left)
h.right = rotateRight(h.right)
h = rotateLeft(h)
colorFlip(h)
'''return''' h
'''void''' deleteMin()
root = deleteMin(root)
root.color = BLACK
'''Node''' moveRedLeftdeleteMin(h : '''Node''' ) <span style="color: #008000">// удаляем узел на нижнем уровне(hдолжен быть красным по инварианту):</span> colorFlip( if h).left == ''null'' '''return''' ''null'' <span style="color:#008000">// Если необходимо, пропушим красную ссылку вниз</span> '''if (!''' isRed(h.right.left) '''&& !'''isRed(h.right = rotateRight(hleft.rightleft)) h = rotateLeftmoveRedLeft(h) colorFlip<span style="color:#008000">// опускаемся на уровень ниже </span> h.left = deleteMin(h.left) '''return''' fixUp(h )
==Асимптотика==
Асимптотика методов в левосторонних красно-черных деревьях эквивалентна асимптотике [[Красно-черное дерево|базовой реализации красно-черных деревьях]].
'''Node''' moveRedRight(h :'''Node''' ): colorFlip(h) '''if''' isRed(h.left.left)) h = rotateRight(h) colorFlip(h) '''return''' h    '''void''' delete(key : '''Key'''): root = delete(root, key) rootСм.color также == BLACK *[[Красно-черное дерево]] '''Node''' delete('''Node''' : h*[[Дерево поиска, '''Key''' : key): '''if''' key.compareTo(h.key) < 0) '''if''' !isRed(h.left) '''&&''' !isRed(h.left.left) h = moveRedLeft(h) h.left = delete(h.left, key) '''else''' '''if''' isRed(h.left)наивная реализация]] h = rotateRight(h) '''if''' key.compareTo(h.key) == 0 '''&&''' (h.right Источники информации== null) '''return''' ''null'' '''if''' !isRed(h.right) '''&&''' !isRed(h.right.left) h = moveRedRight(h) '''if''' key.compareTo(h.key) == 0 h.val = get(h.right* Robert Sedgewick "Left-leaning Red-Black Trees" , min(h.right).key) h.key = min(h.right).key h.right = deleteMin(h.right) '''else''' h.right = delete(h.rightDepartment of Computer Science, key)Princeton University '''return''' fixUp(h)[[Категория: Алгоритмы и структуры данных]]
1632
правки

Навигация