In computer science, a binary search tree (BST), also called an ordered or sorted binary tree, is a rootedbinary treedata structure with the key of each internal node being greater than all the keys in the respective node's left subtree and less than the ones in its right subtree. The time complexity of operations on the binary search tree is linear with respect to the height of the tree.
Binary search trees allow binary search for fast lookup, addition, and removal of data items. Since the nodes in a BST are laid out so that each comparison skips about half of the remaining tree, the lookup performance is proportional to that of binary logarithm. BSTs were devised in the 1960s for the problem of efficient storage of labeled data and are attributed to Conway Berners-Lee and David Wheeler.
The performance of a binary search tree is dependent on the order of insertion of the nodes into the tree since arbitrary insertions may lead to degeneracy; several variations of the binary search tree can be built with guaranteed worst-case performance. The basic operations include: search, traversal, insert and delete. BSTs with guaranteed worst-case complexities perform better than an unsorted array, which would require linear search time.
The complexity analysis of BST shows that, on average, the insert, delete and search takes for nodes. In the worst case, they degrade to that of a singly linked list: . To address the boundless increase of the tree height with arbitrary insertions and deletions, self-balancing variants of BSTs are introduced to bound the worst lookup complexity to that of the binary logarithm. AVL trees were the first self-balancing binary search trees, invented in 1962 by Georgy Adelson-Velsky and Evgenii Landis.
The time complexities of a binary search tree increases boundlessly with the tree height if the nodes are inserted in an arbitrary order, therefore self-balancing binary search trees were introduced to bound the height of the tree to .[4] Various height-balanced binary search trees were introduced to confine the tree height, such as AVL trees, Treaps, and red–black trees.[5]
The AVL tree was invented by Georgy Adelson-Velsky and Evgenii Landis in 1962 for the efficient organization of information.[6][7] It was the first self-balancing binary search tree to be invented.[8]
Overview
A binary search tree is a rooted binary tree in which nodes are arranged in strict total order in which the nodes with keys greater than any particular node A is stored on the right sub-trees to that node A and the nodes with keys equal to or less than A are stored on the left sub-trees to A, satisfying the binary search property.[9]: 298 [10]: 287
Binary search trees are also efficacious in sortings and search algorithms. However, the search complexity of a BST depends upon the order in which the nodes are inserted and deleted; since in worst case, successive operations in the binary search tree may lead to degeneracy and form a singly linked list (or "unbalanced tree") like structure, thus has the same worst-case complexity as a linked list.[11][9]: 299-302
Searching in a binary search tree for a specific key can be programmed recursively or iteratively.
Searching begins by examining the root node. If the tree is nil, the key being searched for does not exist in the tree. Otherwise, if the key equals that of the root, the search is successful and the node is returned. If the key is less than that of the root, the search proceeds by examining the left subtree. Similarly, if the key is greater than that of the root, the search proceeds by examining the right subtree. This process is repeated until the key is found or the remaining subtree is . If the searched key is not found after a subtree is reached, then the key is not present in the tree.[10]: 290–291
Recursive-Tree-Search(x, key)
if x = NIL or key = x.key thenreturn x
if key < x.key thenreturn Recursive-Tree-Search(x.left, key)
elsereturn Recursive-Tree-Search(x.right, key)
end if
The recursive procedure continues until a or the being searched for are encountered.
Iterative search
The recursive version of the search can be "unrolled" into a while loop. On most machines, the iterative version is found to be more efficient.[10]: 291
Iterative-Tree-Search(x, key)
while x ≠ NIL and key ≠ x.key doif key < x.key then
x := x.left
else
x := x.right
end ifrepeatreturn x
Since the search may proceed till some leaf node, the running time complexity of BST search is where is the height of the tree. However, the worst case for BST search is where is the total number of nodes in the BST, because an unbalanced BST may degenerate to a linked list. However, if the BST is height-balanced the height is .[10]: 290
Successor and predecessor
For certain operations, given a node , finding the successor or predecessor of is crucial. Assuming all the keys of a BST are distinct, the successor of a node in a BST is the node with the smallest key greater than 's key. On the other hand, the predecessor of a node in a BST is the node with the largest key smaller than 's key. The following pseudocode finds the successor and predecessor of a node in a BST.[12][13][10]: 292–293
BST-Successor(x)
if x.right ≠ NIL thenreturn BST-Minimum(x.right)
end if
y := x.parent
while y ≠ NIL and x = y.right do
x := y
y := y.parent
repeatreturn y
BST-Predecessor(x)
if x.left ≠ NIL thenreturn BST-Maximum(x.left)
end if
y := x.parent
while y ≠ NIL and x = y.left do
x := y
y := y.parent
repeatreturn y
Operations such as finding a node in a BST whose key is the maximum or minimum are critical in certain operations, such as determining the successor and predecessor of nodes. Following is the pseudocode for the operations.[10]: 291–292
BST-Maximum(x)
while x.right ≠ NIL do
x := x.right
repeatreturn x
BST-Minimum(x)
while x.left ≠ NIL do
x := x.left
repeatreturn x
Insertion
Operations such as insertion and deletion cause the BST representation to change dynamically. The data structure must be modified in such a way that the properties of BST continue to hold. New nodes are inserted as leaf nodes in the BST.[10]: 294–295 Following is an iterative implementation of the insertion operation.[10]: 294
1 BST-Insert(T, z)
2 y := NIL
3 x := T.root
4 while x ≠ NIL do
5 y := x
6 if z.key < x.key then
7 x := x.left
8 else
9 x := x.right
10 end if
11 repeat
12 z.parent := y
13 if y = NIL then
14 T.root := z
15 else if z.key < y.key then
16 y.left := z
17 else
18 y.right := z
19 end if
The procedure maintains a "trailing pointer" as a parent of . After initialization on line 2, the while loop along lines 4-11 causes the pointers to be updated. If is , the BST is empty, thus is inserted as the root node of the binary search tree , if it is not , insertion proceeds by comparing the keys to that of on the lines 15-19 and the node is inserted accordingly.[10]: 295
Deletion
The deletion of a node, say , from the binary search tree has three cases:[10]: 295-297
If is a leaf node, the parent node of gets replaced by and consequently is removed from the , as shown in (a).
If has only one child, the child node of gets elevated by modifying the parent node of to point to the child node, consequently taking 's position in the tree, as shown in (b) and (c).
If has both left and right children, the successor of , say , displaces by following the two cases:
If is 's right child, as shown in (d), displaces and 's right child remain unchanged.
If lies within 's right subtree but is not 's right child, as shown in (e), first gets replaced by its own right child, and then it displaces 's position in the tree.
The following pseudocode implements the deletion operation in a binary search tree.[10]: 296-298
1 BST-Delete(BST, D)
2 if D.left = NIL then
3 Shift-Nodes(BST, D, D.right)
4 else if D.right = NIL then
5 Shift-Nodes(BST, D, D.left)
6 else
7 E := BST-Successor(D)
8 if E.parent ≠ D then
9 Shift-Nodes(BST, E, E.right)
10 E.right := D.right
11 E.right.parent := E
12 end if
13 Shift-Nodes(BST, D, E)
14 E.left := D.left
15 E.left.parent := E
16 end if
1 Shift-Nodes(BST, u, v)
2 if u.parent = NIL then
3 BST.root := v
4 else if u = u.parent.left then
5 u.parent.left := v
5 else
6 u.parent.right := v
7 end if
8 if v ≠ NIL then
9 v.parent := u.parent
10 end if
The procedure deals with the 3 special cases mentioned above. Lines 2-3 deal with case 1; lines 4-5 deal with case 2 and lines 6-16 for case 3. The helper function is used within the deletion algorithm for the purpose of replacing the node with in the binary search tree .[10]: 298 This procedure handles the deletion (and substitution) of from .
Inorder tree walk: Nodes from the left subtree get visited first, followed by the root node and right subtree. Such a traversal visits all the nodes in the order of non-decreasing key sequence.
Preorder tree walk: The root node gets visited first, followed by left and right subtrees.
Postorder tree walk: Nodes from the left subtree get visited first, followed by the right subtree, and finally, the root.
Following is a recursive implementation of the tree walks.[10]: 287–289
Inorder-Tree-Walk(x)
if x ≠ NIL then
Inorder-Tree-Walk(x.left)
visit node
Inorder-Tree-Walk(x.right)
end if
Preorder-Tree-Walk(x)
if x ≠ NIL thenvisit node
Preorder-Tree-Walk(x.left)
Preorder-Tree-Walk(x.right)
end if
Postorder-Tree-Walk(x)
if x ≠ NIL then
Postorder-Tree-Walk(x.left)
Postorder-Tree-Walk(x.right)
visit nodeend if
Without rebalancing, insertions or deletions in a binary search tree may lead to degeneration, resulting in a height of the tree (where is number of items in a tree), so that the lookup performance is deteriorated to that of a linear search.[14] Keeping the search tree balanced and height bounded by is a key to the usefulness of the binary search tree. This can be achieved by "self-balancing" mechanisms during the updation operations to the tree designed to maintain the tree height to the binary logarithmic complexity.[4][15]: 50
Height-balanced trees
A tree is height-balanced if the heights of the left sub-tree and right sub-tree are guaranteed to be related by a constant factor. This property was introduced by the AVL tree and continued by the red–black tree.[15]: 50–51 The heights of all the nodes on the path from the root to the modified leaf node have to be observed and possibly corrected on every insert and delete operation to the tree.[15]: 52
In a weight-balanced tree, the criterion of a balanced tree is the number of leaves of the subtrees. The weights of the left and right subtrees differ at most by .[16][15]: 61 However, the difference is bound by a ratio of the weights, since a strong balance condition of cannot be maintained with rebalancing work during insert and delete operations. The -weight-balanced trees gives an entire family of balance conditions, where each left and right subtrees have each at least a fraction of of the total weight of the subtree.[15]: 62
Binary search trees are used in sorting algorithms such as tree sort, where all the elements are inserted at once and the tree is traversed at an in-order fashion.[23] BSTs are also used in quicksort.[24]
Binary search trees are used in implementing priority queues, using the node's key as priorities. Adding new elements to the queue follows the regular BST insertion operation but the removal operation depends on the type of priority queue:[25]
If it is an ascending order priority queue, removal of an element with the lowest priority is done through leftward traversal of the BST.
If it is a descending order priority queue, removal of an element with the highest priority is done through rightward traversal of the BST.
^Paul E. Black, "red-black tree", in Dictionary of Algorithms and Data Structures [online], Paul E. Black, ed. 12 November 2019. (accessed May 19 2022) from: https://www.nist.gov/dads/HTML/redblack.html
^Adelson-Velsky, Georgy; Landis, Evgenii (1962). "An algorithm for the organization of information". Proceedings of the USSR Academy of Sciences (in Russian). 146: 263–266. English translation by Myron J. Ricci in Soviet Mathematics - Doklady, 3:1259–1263, 1962.
^Knuth, Donald M (1998). "6.2.4". The Art of Computer Programming. Vol. 3 (2 ed.). Addison Wesley. ISBN9780201896855. The 2–3 trees defined at the close of Section 6.2.3 are equivalent to B-Trees of order 3.
Season of television series Season of television series Arrested DevelopmentSeason 3DVD coverStarring Jason Bateman Portia de Rossi Will Arnett Michael Cera Alia Shawkat Tony Hale David Cross Jeffrey Tambor Jessica Walter Country of originUnited StatesNo. of episodes13ReleaseOriginal networkFoxOriginal releaseSeptember 19, 2005 (2005-09-19) –February 10, 2006 (2006-02-10)Season chronology← PreviousSeason 2Next →Season 4List of episodes The third season of the te...
American politician E. Finley CromwellMember of the Virginia Senatefrom the 33rd districtIn officeDecember 4, 1901 – January 10, 1906Preceded byHarry L. MaynardSucceeded byJohn C. NiemeyerMember of the Virginia House of Delegates from Norfolk CountyIn officeJanuary 30, 1900 – December 4, 1901Preceded byM. S. NewberneSucceeded byCharles T. Bland Personal detailsBornEbenezer Finley Cromwell(1855-07-03)July 3, 1855DiedApril 21, 1947(1947-04-21) (aged 91)Political party...
Capital and largest city of Greenland Capital city in Greenland, Kingdom of DenmarkNuukCapital city(left to right, top to bottom:) Downtown Nuuk, with Katuaq in the foreground; Sermitsiaq mountain overlooking Nuussuaq; Nuussuaq district; Qernertunnguit, neighbourhood in the Quassussuup Tungaa district; the skyline at night with the aurora borealis above FlagCoat of armsNuukLocation within GreenlandShow map of GreenlandNuukNuuk (North America)Show map of North AmericaCoordinates: 64°10′53�...
Tata SonsJenisSwastaDidirikan1868; 154 tahun lalu (1868)PendiriTataKantorpusatBombay House, Mumbai, Maharashtra, IndiaWilayah operasiSeluruh duniaTokohkunciKeluarga TataRatan Tata(Chairman Emeritus)Pallonji MistryShapoor MistryNatarajan Chandrasekaran(Chairman)PemilikTata Trusts (66%)Shapoorji Pallonji Group (18%)Situs webwww.tata.com Tata Sons Private Limited adalah perusahaan induk dari Tata Group, yang memegang sebagian besar saham dari perusahaan yang ada di dalam Tata Group, termasu...
هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (يوليو 2019) إريك سفينسون (منافس ألعاب قوى) معلومات شخصية الميلاد 10 سبتمبر 1903[1] يونشوبينغ الوفاة 22 سبتمبر 1986 (83 سنة) [2] فالكنبرغ الطول 180 سنتيمتر...
Hagai LeviHagai LeviBorn (1963-07-02) 2 July 1963 (age 60)Sha'alvim, IsraelOccupation(s)television creator, writer, director, producer Hagai Levi (Hebrew: חגי לוי; born on 2 July 1963) is an Israeli television creator, writer, director, and producer. Early life and education Levi was born in Sha'alvim, Israel in 1963. He studied psychology at Bar-Ilan University but left to complete his mandatory military service. Levi served in the Israeli Ground Forces before studying film at Tel...
American businessman This article is about the businessman. For the baseball player born in 1856, see Charlie Guth. For the baseball player born in 1947, see Bucky Guth. Charles Godfrey GuthPresident of Pepsi-ColaIn office1931-1939Preceded byRoy MegargelSucceeded byWalter Staunton Mack Jr. Personal detailsBornJune 3, 1877Philadelphia, PennsylvaniaDiedMay 24, 1948(1948-05-24) (aged 70)Baltimore, MarylandNationalityAmerican Charles Godfrey Guth (June 3, 1877 – May 24, 1948) ...
For other uses, see Khalifa (disambiguation). Look up khalifa in Wiktionary, the free dictionary. Khalifa خَليفةAbu Bakr, the first KhalifaPronunciationArabic: [xaliːfa]GenderMaleLanguage(s)ArabicOriginMeaningLeader, Successor, Steward, DeputyRegion of originArabia Islamic CaliphateOther namesAlternative spellingKhalifah, Khaleefa, Khaleefah, CaliphVariant form(s)Khalifeh (Persian), Kalifa (West African) Khalifa or Khalifah (Arabic: خليفة; commonly caliph in English) is a ...
This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these template messages) This article relies largely or entirely on a single source. Relevant discussion may be found on the talk page. Please help improve this article by introducing citations to additional sources.Find sources: Isochronous signal – news · newspapers · books · scholar · JSTOR (November 2020) This article inc...
Streetcar operator in Toronto, Canada, between 1891 and 1921 Toronto Railway CompanySingle-truck open car on Dovercourt route, 1899OverviewHeadquartersToronto, OntarioLocaleToronto, OntarioDates of operation1891–1921PredecessorToronto Street RailwaySuccessorToronto Transportation CommissionTechnicalTrack gauge4 ft 10+7⁄8 in (1,495 mm) Toronto gauge The Toronto Railway Company (TRC) was the operator of the streetcar system in Toronto between 1891 and 1921. It el...
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: Spectacular! soundtrack – news · newspapers · books · scholar · JSTOR (March 2012) (Learn how and when to remove this template message) 2009 soundtrack album by Spectacular! castSpectacular!: Music from the Nickelodeon Original MovieSoundtrack album...
Phenomenon in physics An example of a Doppler broadened line profile. The solid line represents an un-broadened emission profile, and the dashed line represents a broadened emission profile. In atomic physics, Doppler broadening is broadening of spectral lines due to the Doppler effect caused by a distribution of velocities of atoms or molecules. Different velocities of the emitting (or absorbing) particles result in different Doppler shifts, the cumulative effect of which is the emission (ab...
Ukrainian 125th Territorial Defense Forces Brigade 125th Independent Brigade of the Territorial Defense ForcesUkrainian: 125-та окрема бригада територіальної оборониActive27 February 2022 - presentCountry UkraineBranchArmed Forces of UkraineTypeMilitary reserve forceRoleLight infantryPart of Territorial Defense ForcesGarrison/HQ LvivMUN A7381[1]Websitehttps://www.125tro.lviv.ua/Military unit The 125th Independent Brigade of the T...
United States historic placeWesley Plattenburg HouseU.S. National Register of Historic PlacesAlabama Register of Landmarks and Heritage As recorded by the Historic American Buildings Survey in 1934Show map of AlabamaShow map of the United StatesLocation601 Washington St., Selma, AlabamaCoordinates32°24′50″N 87°1′20″W / 32.41389°N 87.02222°W / 32.41389; -87.02222Built1842Architectural styleGreek Revival, ItalianateNRHP reference No.92001827 ...
Artikel ini membutuhkan rujukan tambahan agar kualitasnya dapat dipastikan. Mohon bantu kami mengembangkan artikel ini dengan cara menambahkan rujukan ke sumber tepercaya. Pernyataan tak bersumber bisa saja dipertentangkan dan dihapus.Cari sumber: Sainan Sagiman – berita · surat kabar · buku · cendekiawan · JSTOR (Sept 2022) Sainan SagimanGubernur Sumatera Selatan ke-10Masa jabatan1978–1988PresidenSoehartoPendahuluAsnawi Mangku AlamPenggantiRamli...
Chalcidian type helmet, circa 500 BC, exhibit in The Walters Art Gallery, Baltimore. A Chalcidian helmet or Chalcidian type helmet was a helmet made of bronze and worn by ancient warriors of the Hellenic world, especially popular in Greece in the fifth and fourth centuries BC. The helmet was also worn extensively in the Greek (southern) parts of Italy in the same period. Terminology The helmet is so-called because it was first, and is most commonly, depicted on pottery once thought to derive ...
Washington, D.C. politician Elissa SilvermanMember of the Council of the District of Columbia at-largeIn officeJanuary 2, 2015 – January 2, 2023Preceded byDavid CataniaSucceeded byKenyan McDuffie Personal detailsBorn1972 or 1973 (age 50–51)[1]Baltimore, Maryland, U.S.Political partyDemocratic (Before 2014)Independent (2014–present)EducationBrown University (BA)University of Maryland, College Park Elissa Silverman is an American politician and reporter f...
Village in Podlaskie Voivodeship, PolandWnory-WandyVillageWnory-WandyCoordinates: 53°3′N 22°35′E / 53.050°N 22.583°E / 53.050; 22.583Country PolandVoivodeshipPodlaskieCountyWysokie MazowieckieGminaKobylin-BorzymyPopulation140Time zoneUTC+1 (CET) • Summer (DST)UTC+2 (CEST)Vehicle registrationBWM Wnory-Wandy [ˈvnɔrɨ ˈvandɨ] is a village in the administrative district of Gmina Kobylin-Borzymy, within Wysokie Mazowieckie County, Podlaskie...
American record label For the 1956–1958 music label also originally owned by Atlantic Records, see East-West Records. 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: East West Records – news · newspapers · books · scholar · JSTOR (August 2020) (Learn how and when to remove this template message) East West ...