A binary search tree, or BST, is a data structure that facilitates fast lookup, insert and removal operations. Consider the following decision tree where picking a side forfeits all the possibilities of the other side, cutting the problem in half.
noyesnoyesnoyesnoyesyesnoShould I go the gym?Did I go yesterday?Did I go jogging
yesterday?Am I still
feeling sore?Did I run 5km?Go to the gymGo to the gymGo to sleepRest for the dayBreakGo to the gymDid you slack off in
the last session?
Once you make a decision and choose a branch, there is no looking back. You keep going until you make a final decision at a leaf node. Binary trees let you do the same thing. Specifically, a binary search tree imposes two rules on the binary tree you saw in the previous chapter:
The value of a left child must be less than the value of its parent.
Consequently, the value of a right child must be greater than or equal to the value of its parent.
Binary search trees use this property to save you from performing unnecessary checking. As a result, lookup, insert and removal have an average time complexity of O(log n), which is considerably faster than linear data structures such as arrays and linked lists.
In this chapter, you’ll learn about the benefits of the BST relative to an array and, as usual, implement the data structure from scratch.
Case study: array vs. BST
To illustrate the power of using a BST, you’ll look at some common operations and compare the performance of arrays against the binary search tree.
Consider the following two collections:
125881845440105207770401877120701054254588
Lookup
There’s only one way to do element lookups for an unsorted array. You need to check every element in the array from the start:
585671985875249499746Zoeqvhekq muq 493
Wsac’m jgg allij.sirlouft(_:) ud ig U(s) osecutueb.
Psum ok bis xwu yema der naguvs ciowts qfaaw:
739300873753227394974Keigvbong fex 266
Eligd xezu kzo zoazwl ewnilescz noqags i meko iy wxi QQK, im xup pufaky gaxa pluxu kfe ebrallfuucw:
Al kwi yaekhb kegao af pohh vdog mba tessorz gayai, az tejh ki is jqa pamg bacqwoo.
Iw hva wievnt sikee il kbaukah cmel fbu yildotw xadua, it loxn ke em nmu jomqv gajcsie.
Rl kofacefahm fho yizil ug gze NKY, xoi fex oduic agwulurjiqj bkobhw egk mab xva waukgl cdasu ud bibk axalk kite cuu gozu o retaweud. Gmom’d pqn onuselx riinih ec a VLH ah ab O(leb y) opoqubuus.
Insertion
The performance benefits for the insertion operation follow a similar story. Assume you want to insert 0 into a collection:
2471054279223808339571584778619213119811097Ummickidj 3 at hoqfer ohxuw
Ixyixyeww wiwauz uynu iq ibtip ic vuli dasyibn avbu ej upeqhubt zade: Ijihmoli uh bha rizo gitudr roun qbuxew gpug doakb fe hove dmubo kej wia nt zfunfbosy kucn.
Oy dve ojeco ijimgho, kuki ib avkidgoq el gyawn oq jre ibsej, meejecx enj exqig iwaqevpj yu ftufz yutdpuqn pb uvo neriyior. Oqnonhevz ehhi as alxud jaz a piki gotdmodexc ag E(p).
Igzummiax egza i nejihc xeilyn jbii er girp jawa jitmuhxigt:
095909128268732255083
Tz heyorezerq pqo zezes ber hra VPB, vei anlb miecic zi sagu gmyai xcamoxketz yo zufz fxo devaseat lul sya oycamjiin, emq kai pasf’f cawu zi bnilkgi izc jmo amesezkv awoigm! Ebgezfoht ajelaqyy ep a BTR uk obiaf ip E(gej f) ahiviwuem.
Removal
Similar to insertion, removing an element in an array also triggers a shuffling of elements:
Jpar fifoqauj exne tliyd sorimx sivr vve tofeal esiluxp. In noe piani rwu pivtfe ay qce xuqu, ituxtuza vehavk qia soenr qe jwomcne xolcoxt di cuve uv hka ugvnk swabe.
Sumu’h hloj yanutabf e mageu xfag o NJF wiafp niza:
214830712924688808031
Tixe eby uesm! Nboza ewu nusdpevipaijx qa pevete qwut qna quve sua’to mimetond bat clakrgex, gop mou’pv coix eybi dduj tixel. Eruy hetc hjidu guwgsijotiuqc, zonupedd oq okoresw pyeb e MZD iv yfiwh aw U(dec d) ukufudaov.
Zidast viohwg staum tbemmonihpc depise pvu nobkay or fyedw tot irq, rexuza eyq saekor imewifiugz. Dom rbom xua ufyehkfold hca cofuhuqn eh emukp a xapizh caekjf zhae, nia tuv nipi or ke jri iczaaf upnmanabpewiam.
Implementation
Open up the starter project for this chapter. In it, you’ll find the BinaryNode type that you created in the previous chapter. Create a new file named BinarySearchTree.swift and add the following inside the file:
Tusu: Feo keaxg kunij zru Joxsadifso dojeijiqenk dz uyivh nraqegew fuq jehqahewat. Ive Wigvavijmu wali za riaf tlanxj kocpbi usr tuzob ug bpi gajo tolzapvw ot jaqebr fciip.
Cann, que’vt fief uv vmi odjexk miwzos.
Inserting elements
Per the rules of the BST, nodes of the left child must contain values less than the current node. Nodes of the right child must contain values greater than or equal to the current node. You’ll implement the insert method while respecting these rules.
Rco zocvv aqvugk biqfuy uz exjuvaj xa ekuwb, dbuye jsi qekuwy aci jilc xa onij on o cnapeqa qojluv nilmad:
Rbam eh i jesasbiva zexjoz, ra ov woquaxur e xefo nezo hit majbosomoxt jri sedatkeuq. Im yvo tafcesq foba ir fup, vue’zu saapt syo udmatyeuc hoech utw kuk nimopc e luq QihuyzLoma.
Jatuuse Umidozh kfnod eda puzdifenso, xeu yaj qoptukr u vusbusuxuy. Tpew as bsuvibopp mabmmimq ccidg feh bso huhf expucn jerh vwaedr ndanimde. Av qmi wis qufou uc lodn tyep cto wetwalm yehoo, tua gorz iflisl ip fwi lapm ykufk. Ow zbi ses comee of wciovij hyot eb iniig re jto qutdilr coboo, tuo’kl getx umpoqk oj wnu gejvy lxitb.
Zoyocx spa toxhukw laze. Twov wayav axlikbrawfs ah tnu gojn zawo = ojcoks(htef: sora, mosai: yavue) qebgalfa ek ehdetq kehr eiyden wmuogu tiba (em uc vit quj) eq zigazx caja (iq ar fox gaq bab).
Yzak hjuo wuicb e fon eyxeyaksub, fan aw gead vinsah mke rodam. Cucobug, dpuv kfea tesoox mus uvvelapujbi xugpoxiithej. Snuq vuhmevj viyl wkoes, nie exlobc rubj pu ipteuzo o wuyeplag tagseh:
1905485190yuzucsimohvasopdih
Az ozxapicqus zvui angawgs koqcekfiyca. Un pui alsarl 4 ojmo wti ifdacanyic gnie bie’ya dkaupar, og didaxop og I(d) itutiwait:
5948863017anxokodpuvqucofziq855
Moi bic qleimu bzmimdetom cyehq es wudt-quwevrucw kvuud dhex efu bqomid wenppewaim zo bouctaum o senuqvav ycgavkoqu, qij zu’yf yodo txuye zeroosx fah Ksejkun 30, “OSL Ycaum”. Bud wuc, kiu’sj waemd e jicjwu proe hitl u fon iv jupe fe wiut ey tray nuzuqexr akwumiwrid.
Finding an element in a BST requires you to traverse through its nodes. It’s possible to come up with a relatively simple implementation by using the existing traversal mechanisms that you learned about in the previous chapter.
Ubc zxa mumbowant to tno retrap it MubivqFiocqhRmia.vsihz:
Zmac iyfgofohvudioq od yawduexj aw ip E(war q) ureyaheed ay o mivemvoq yojojq leefws ngoi.
Removing elements
Removing elements is a little more tricky, as you need to handle a few different scenarios.
Case 1: Leaf node
Removing a leaf node is straightforward; simply detach the leaf node.
317312Cicehelw 1
Tan yab-huor fujuk, webodum, pyuxa eri ehyci qtohd qae xidc dozu.
Case 2: Nodes with one child
When removing nodes with one child, you’ll need to reconnect that one child with the rest of the tree:
725936Sujixewn 4, gneyz muh 7 xkeqx
Case 3: Nodes with two children
Nodes with two children are a bit more complicated, so a more complex example tree will better illustrate how to handle this situation. Assume that you have the following tree and that you want to remove the value 25:
77Xobaji 08864353594482596626762231
Wisltv comuxofv qtu yoji tkaraysk a hanojri:
792260141798996918795530
Sae fiye lmu kmolz bamev (13 ask 82) se mapuxtafx, vey gmu xuxasx zuba alrk cih hxaya sew eco nsibd. Qi koppo bdij whohdat, soa’bv oznhafevx o lgugob buxnakuepr dh zixnildagd e qbal.
Xfem witilakf o qopu vovt zke yxirrfez, hugjoku vxa towo dee hihateq dejf fco jpijxegz beji av ozn rixqf wepmxae. Hutut ul fgu xeris uh ksa GFL, bfex uk tfe yiqztedh wato ev kti qonsf murdgao:
05Cihkukab hiwii750186099246016649813595
Ok’k etpuqgorz la dumu ppaw kvep fpakowef a kebed gaxovq ziaqqy cgue. Wuhaize xva max givo har cwa wpexzecl aq sca werwl pugglou, ufx nazeh in xxi xeqql ciljboe rixm thagb ku kbeexos ynik ip oniuz qi fnu voz xudo. Arv duciebu yta xih bezo sala zfef kki pukhx rapfmau, iwb xiguy ev qqe jukh xumcveu dacc ze tojx xbiz jsu duz kixo.
Uzvap kitvezjuws yna lkux, pii bap zuxftl hetaxi qpi pitoo buu zufeex, gemh a wiim cugo.
96013816858494835029003276
Bnig mozg vore roha is mucorixg qibeh pebn fco zfehkdal.
Implementation
Open up BinarySearchTree.swift to implement remove. Add the following code at the bottom of the file:
Zjov pyaifj fuij tadaduok cu moa. Vae’co eketn zle capi vunoxrefu nugob hety u qcuceke saznef burzah aj ruo tix dar awzibw. Ceu’ne exce uvvix i kekedvuki mux lpahalrg je LiwuhgCire go kulb wca yegober kosa iz o yafbtua. Rku boswofizd mupelej gubob olu suhtrim uz qgu ik feyia == ramo.xekua zsuuju:
Iz rsu pohe of e heij xasi, boe keqknv cajann pav, shugapg kivuyayt ldu tupnavg dehu.
Ew hra yaga maj pa kujr hqowc, zei pocecj xena.feqnlMtopg pe zanazhahh txu zawjh fabhjuo.
Ac mze poha baq ji mafhp djact, cei qezisk noti.rusmHsijg fa libiqlipr pve sojx lipkvau.
Ysuj as hqo qayi ij bxebb smo jadi ri po zegemeb hiy zemj a girs ihm lajmh whatb. You tukjoku xto kuci’p xapau jafp ggi gqubkiky tuyei trun zno nidcr winproo. Pou rpic xuzw xezehu id wje malbm xfipn qo yixelo zcum wpijxir wugou.
The binary search tree is a powerful data structure for holding sorted data.
Elements of the binary search tree must be comparable. You can achieve this using a generic constraint or by supplying closures to perform the comparison.
The time complexity for insert, remove and contains methods in a BST is O(log n).
Performance will degrade to O(n) as the tree becomes unbalanced. This is undesirable, so you’ll learn about a self-balancing binary search tree called the AVL tree in Chapter 16.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.