2–3–4 tree

2–3–4 tree
Typetree
Time complexity in big O notation
Operation Average Worst case
Search O(log n) O(log n)
Insert O(log n) O(log n)
Delete O(log n) O(log n)
Space complexity
Space O(n) O(n)

In computer science, a 2–3–4 tree (also called a 2–4 tree) is a self-balancing data structure that can be used to implement dictionaries. The numbers mean a tree where every node with children (internal node) has either two, three, or four child nodes:

  • a 2-node has one data element, and if internal has two child nodes;
  • a 3-node has two data elements, and if internal has three child nodes;
  • a 4-node has three data elements, and if internal has four child nodes;

2–3–4 trees are B-trees of order 4;[1] like B-trees in general, they can search, insert and delete in O(log n) time. One property of a 2–3–4 tree is that all external nodes are at the same depth.

2–3–4 trees are closely related to red–black trees by interpreting red links (that is, links to red children) as internal links of 3-nodes and 4-nodes, although this correspondence is not one-to-one.[2] Left-leaning red–black trees restrict red–black trees by forbidding nodes with a single red right child, which yields a one-to-one correspondence between left-leaning red–black trees and 2–3–4 trees.

Properties

  • Every node (leaf or internal) is a 2-node, 3-node or a 4-node, and holds one, two, or three data elements, respectively.
  • All leaves are at the same depth (the bottom level).
  • All data is kept in sorted order.

Insertion

To insert a value, we start at the root of the 2–3–4 tree:

  1. If the current node is a 4-node:
    • Remove and save the middle value to get a 3-node.
    • Split the remaining 3-node up into a pair of 2-nodes (the now missing middle value is handled in the next step).
    • If this is the root node (which thus has no parent):
      • the middle value becomes the new root 2-node and the tree height increases by 1. Ascend into the root.
    • Otherwise, push the middle value up into the parent node. Ascend into the parent node.
  2. Find the child whose interval contains the value to be inserted.
  3. If that child is a leaf, insert the value into the child node and finish.
    • Otherwise, descend into the child and repeat from step 1.[3][4]

Example

To insert the value "25" into this 2–3–4 tree:

  • Begin at the root (10, 20) and descend towards the rightmost child (22, 24, 29). (Its interval (20, ∞) contains 25.)
  • Node (22, 24, 29) is a 4-node, so its middle element 24 is pushed up into the parent node.
  • The remaining 3-node (22, 29) is split into a pair of 2-nodes (22) and (29). Ascend back into the new parent (10, 20, 24).
  • Descend towards the rightmost child (29). (Its interval (24, ∞) contains 25.)
  • Node (29) has no leftmost child. (The child for interval (24, 29) is empty.) Stop here and insert value 25 into this node.

Deletion

The simplest possibility to delete an element is to just leave the element there and mark it as "deleted", adapting the previous algorithms so that deleted elements are ignored. Deleted elements can then be re-used by overwriting them when performing an insertion later. However, the drawback of this method is that the size of the tree does not decrease. If a large proportion of the elements of the tree are deleted, then the tree will become much larger than the current size of the stored elements, and the performance of other operations will be adversely affected by the deleted elements.

When this is undesirable, the following algorithm can be followed to remove a value from the 2–3–4 tree:

  1. Find the element to be deleted.
    • If the element is not in a leaf node, remember its location and continue searching until a leaf, which will contain the element's successor, is reached. The successor can be either the largest key that is smaller than the one to be removed, or the smallest key that is larger than the one to be removed. It is simplest to make adjustments to the tree from the top down such that the leaf node found is not a 2-node. That way, after the swap, there will not be an empty leaf node.
    • If the element is in a 2-node leaf, just make the adjustments below.

Make the following adjustments when a 2-node – except the root node – is encountered on the way to the leaf we want to remove:

  1. If a sibling on either side of this node is a 3-node or a 4-node (thus having more than 1 key), perform a rotation with that sibling:
    • The key from the other sibling closest to this node moves up to the parent key that overlooks the two nodes.
    • The parent key moves down to this node to form a 3-node.
    • The child that was originally with the rotated sibling key is now this node's additional child.
  2. If the parent is a 2-node and the sibling is also a 2-node, combine all three elements to form a new 4-node and shorten the tree. (This rule can only trigger if the parent 2-node is the root, since all other 2-nodes along the way will have been modified to not be 2-nodes. This is why "shorten the tree" here preserves balance; this is also an important assumption for the fusion operation.)
  3. If the parent is a 3-node or a 4-node and all adjacent siblings are 2-nodes, do a fusion operation with the parent and an adjacent sibling:
    • The adjacent sibling and the parent key overlooking the two sibling nodes come together to form a 4-node.
    • Transfer the sibling's children to this node.

Once the sought value is reached, it can now be placed at the removed entry's location without a problem because we have ensured that the leaf node has more than 1 key.

Deletion in a 2–3–4 tree is O(log n), assuming transfer and fusion run in constant time (O(1)).[3][5]

Parallel operations

Since 2–3–4 trees are similar in structure to red–black trees, parallel algorithms for red–black trees can be applied to 2–3–4 trees as well.

See also

References

  1. ^ Knuth, Donald (1998). Sorting and Searching. The Art of Computer Programming. Vol. 3 (Second ed.). Addison–Wesley. ISBN 0-201-89685-0.. Section 6.2.4: Multiway Trees, pp. 481–491. Also, pp. 476–477 of section 6.2.3 (Balanced Trees) discusses 2–3 trees.
  2. ^ Sedgewick, Robert (2008). "Left-Leaning Red–Black Trees" (PDF). Left-Leaning Red–Black Trees. Department of Computer Science, Princeton University.
  3. ^ a b Ford, William; Topp, William (2002), Data Structures with C++ Using STL (2nd ed.), New Jersey: Prentice Hall, p. 683, ISBN 0-13-085850-1
  4. ^ Goodrich, Michael T; Tamassia, Roberto; Mount, David M (2002), Data Structures and Algorithms in C++, Wiley, ISBN 0-471-20208-8
  5. ^ Grama, Ananth (2004). "(2,4) Trees" (PDF). CS251: Data Structures Lecture Notes. Department of Computer Science, Purdue University. Retrieved 2008-04-10.

Read other articles:

هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (مارس 2020) مجموعة العمل المدنية (بالإنجليزية:Civilian Labor Group، اختصارًا CLG) هي منظمات من مواطنين ألمان أو أوروبيين آخرين يعملون لدى الجيش الأمريكي في أوروبا. وغالبا ما يتم ارتد

 

هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (مارس 2023) الحويصلات الدقيقة (الإكتوسومات، أو الجسيمات الدقيقة) هي نوع من الحويصلات خارج الخلية التي تتحرر من غشاء الخلية.[1] في الكائنات متعددة الخلايا، توجد الحويصل

 

Placa catari no padrão atual, utilizado desde 2011 As placas de identificação de veículos no do Catar começaram a ser utilizadas na década de 1950.[1] A versão atual foi adotada em 2012[2], numa versão das placas utilizadas desde 1973. O código de registro internacional de veículos do Catar é Q. Em um leilão realizado em 2016, a placa de número 411 foi vendida por 960000 dólares.[3][4] Galeria Uma placa catari no padrão utilizado de 1997 a 2011 Placa de veículo policial Refer...

المحمدية الصغيرة تقسيم إداري البلد المغرب  الجهة مراكش آسفي الإقليم مراكش الدائرة الويدان الجماعة القروية الويدان المشيخة المحمدية السكان التعداد السكاني 455 نسمة (إحصاء 2004)   • عدد الأسر 80 معلومات أخرى التوقيت ت ع م±00:00 (توقيت قياسي)[1]،  وت ع م+01:00 (توقيت صيفي)[1&...

 

  لمعانٍ أخرى، طالع بيل بلاك (توضيح). هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (يوليو 2019) بيل بلاك   معلومات شخصية اسم الولادة (بالإنجليزية: William Thomas Blackwell III)‏  الميلاد سنة 1960 (العمر 62–63 سنة)  لونغ بي

 

American journalist (1953–2023) Steve PoolPool in 2015Born(1953-11-05)November 5, 1953DiedNovember 22, 2023(2023-11-22) (aged 70)Seattle, Washington, U.S.EducationUniversity of Washington (BA, Communications & Speech)OccupationJournalistYears active1977–2019Notable creditKOMO 4 News (1977–2019)SpouseMichelleChildren2 Steve Pool (November 5, 1953 – November 22, 2023) was an American weather presenter and journalist. He began covering sports for KOMO-TV in Seattle in 1977 ...

Università Cattolica del Sacro Cuore LibraryLocationMilan, ItalyEstablished1921Access and useAccess requirementsdepends on libraryOther informationWebsiteSistema Bibliotecario e Documentale d'Ateneo The Università Cattolica del Sacro Cuore Library was established (founded) in 1921 by Agostino Gemelli, who based its design and organisation on that of highly prestigious foreign libraries. All the libraries of the four UCSC campuses (Milan, Brescia, Piacenza-Cremona and Rome) use a centralized...

 

Chinese desktop and web mapping service application You can help expand this article with text translated from the corresponding article in Chinese. (April 2015) Click [show] for important translation instructions. Machine translation, like DeepL or Google Translate, is a useful starting point for translations, but translators must revise errors as necessary and confirm that the translation is accurate, rather than simply copy-pasting machine-translated text into the English Wikipedia. D...

 

Rezlan Ishar JenieLahir6 Januari 1952 (umur 71)JakartaPekerjaanDiplomatDikenal atasDuta BesarSuami/istriSally Yukari BudiardjoAnak2Orang tuaAdlinsjah Jenie (ayah)Chailan Sjamsoe (ibu) Drs. Rezlan Ishar Jenie (lahir 6 Januari 1952) adalah seorang diplomat Indonesia. Sejak tahun 2010, ia menjabat sebagai Duta Besar Luar Biasa dan Berkuasa Penuh Republik Indonesia untuk Prancis merangkap Kepangeranan Monako dan Kepangeranan Andorra serta UNESCO.[1] Sebelumnya, ia menjabat sebagai Di...

SukahajiDesaKantor Desa Sukahaji, Sukawening, GarutNegara IndonesiaProvinsiJawa BaratKabupatenGarutKecamatanSukaweningKode Kemendagri32.05.15.2007 Luas1220,99 km²Jumlah penduduk6.227 jiwa Desa Sukahaji adalah sebuah desa di kecamatan Sukawening, Kabupaten Garut, Jawa Barat, Indonesia sama seperti Pemerintahan Desa pada umumnya Desa Sukahaji juga dipimpin oleh seorang Kepala Desa, yang sekarang dijabat oleh seorang Kepala Desa terpilih Ir. Asep Sukwanda Jaya (Periode 2016-2021). Sejarah ...

 

Anglo-Australian multinational mining company Rio Tinto GroupRio Tinto plc & Rio Tinto LimitedRio Tinto headquarters in Melbourne, AustraliaTypeDual-listed companyTraded asASX: RIOLSE: RIONYSE: RIOFTSE 100 Index componentS&P/ASX 200 componentIndustryMetals and MiningFounded29 March 1873; 150 years ago (1873-03-29)HeadquartersLondon, EnglandMelbourne, AustraliaArea servedWorldwideKey peopleDominic Barton(Chairman)Jakob Stausholm(Chief executive)Products...

 

Yosua 12Kitab Yosua lengkap pada Kodeks Leningrad, dibuat tahun 1008.KitabKitab YosuaKategoriNevi'imBagian Alkitab KristenPerjanjian LamaUrutan dalamKitab Kristen6← pasal 11 pasal 13 → Yosua 12 (disingkat Yos 12) adalah pasal kedua belas Kitab Yosua dalam Alkitab Ibrani dan Perjanjian Lama di Alkitab Kristen yang memuat riwayat Yosua dalam memimpin orang Israel menduduki tanah Kanaan.[1] Pasal ini berisi daftar raja-raja Kanaan yang dikalahkan oleh orang Israel.[2]...

Unicameral legislature of Rajasthan, India This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Rajasthan Legislative Assembly – news · newspapers · books · scholar · JSTOR (December 2023) (Learn how and when to remove this template message) Rajasthan Legislative Assembly16th Rajasthan AssemblyTypeTypeUnicameral ...

 

South Korean actor This article is about the actor. For the poet, see Kim Kwang-kyu. In this Korean name, the family name is Kim. Kim Kwang-kyuBorn (1967-12-08) December 8, 1967 (age 55)Yeongdo District, Busan, South KoreaEducationBusan Arts CollegeKorea National Open UniversityOccupationActorYears active1999–presentAgentThink Entertainment[1]Korean nameHangul김광규Hanja金光奎Revised RomanizationGim Gwang-gyuMcCune–ReischauerKim Kwangkyu Kim Kwang-kyu (born Decembe...

 

Theater in Lyon, FranceLes SubsistancesGeneral informationTypeTheaterLocation1st arrondissement of Lyon, Lyon, FranceCurrent tenantsLes SubsistancesInaugurated2001OwnerCity of LyonWebsitewww.les-subs.com Les Subsistances is a cultural centre of diffuse artistic production and located in the 1st arrondissement of Lyon. Since 2007, it has housed a creative laboratory (theater, dance and contemporary circus) and the École nationale des beaux-arts de Lyon. The site has 22,500 square metres of bu...

This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Rip It Off Stroke 9 album – news · newspapers · books · scholar · JSTOR (February 2013) (Learn how and when to remove this template message) 2002 studio album by Stroke 9Rip It OffStudio album by Stroke 9ReleasedOctober 1, 2002GenreAlternative rock...

 

Administrative divisions of Bulgaria Politics of Bulgaria Constitution1879194719711991 Presidency President (list) Rumen Radev Vice President Iliana Iotova ExecutiveLegislative Government Prime Minister (list) Nikolay Denkov National Assembly Speaker: Vezhdi Rashidov LawJudiciary Nationality law Human rights Courts Constitutional Court Supreme Administrative Court Supreme Court of Cassation Office of the General Prosecutor Major political partiesPPGERBDPSBulgarian Socialist PartyDemocratic Bu...

 

Dana Veldáková Datos personalesNacimiento Rožňava (Eslovaquia)3 de junio de 1981Nacionalidad(es) EslovacaCarrera deportivaDeporte Atletismo               Medallero Atletismo Eslovaquia Eslovaquia Europeo Pista Cubierta BronceParís 2011Triple salto [editar datos en Wikidata] Dana Veldáková (Eslovaquia, 3 de junio de 1981) es una atleta eslovaca especializada en la prueba de triple salto, en la que consiguió...

American baseball player Baseball player James MarvelMarvel with the Indianapolis Indians in 2021Free agent PitcherBorn: (1993-09-17) September 17, 1993 (age 30)San Francisco, California, U.S.Bats: RightThrows: RightProfessional debutMLB: September 8, 2019, for the Pittsburgh PiratesNPB: July 16, 2023, for the Hokkaido Nippon-Ham FightersMLB statistics (through 2019 season)Win–loss record0–3Earned run average8.31Strikeouts9NPB statistics (through 2023 se...

 

السلفادور دولة لاتينية تقع في شمال أمريكا الوسطى وتنقسم إلى 14 إدارة (departamentos) للأغراض الإدارية وهي بدورها تنقسم إلى 262 بلدية (municipios). والسلفادور دولة مركزية. الإدارات # العلم الإدارة العاصمة المساحة (كم2) تعداد السكان[1] (2013) 1 إدارة أهواشابان Ahuachapán أهواتشابان Ahuachapán 1,239.6 333,...

 

Strategi Solo vs Squad di Free Fire: Cara Menang Mudah!