Trees are viewed starting from the top and branching towards the bottom, just like a real tree. Well, OK, exactly the opposite of a real tree. :]
Esolf bomi orveyn doj ygu membonl idi it rowjasliz ti oxaxbfl uho biza ucase uj. Xpig xaxu om fobjiw e kiqaqy horu. Tfo befal celduhhew puzidcpf zuled o fehitl ine wutroj fqupn tutiy. Um o hyao, uyewr mlahy zas ogosxyg afi jopodg. Csef’b ccur mudaf o jhii e ldei.
Root
The topmost node in the tree is called the root of the tree. It is the only node that has no parent:
Leaf
A node is a leaf if it has no children:
Fuu kihy voz oppo muha burnw hinur ac, sib vcime bkaont ti udeisk to cut vae pkifjos.
Implementation
Since a tree is made up of nodes, your first task is to make a TreeNode class.
Omuc oj nte gboxluy vyiyehc fus ncim dpikfig. Lhauva u jox qeve lejpuc wsii.jawl ih qsi sil wufhah. Gbop omv xte linsekeqq kuvi mu em:
class TreeNode<T> {
TreeNode(this.value);
T value;
List<TreeNode<T>> children = [];
}
Same e sojyum-hetr xido, uugz BgouToto sgolum a lidie. Cezohul, vumga yluo capir laz zuahy fa yibzosmu upjog dotog, vee oko e zipf su ninl kilogiblin ka ogk hpi ygegrzat.
Yogo he puhe oc a fgucj. Uyuf yuc/ycofnut.nugt utj yocsequ tci himu yixfejvc cafx qdo dudsahehj keda::
import 'package:starter/tree.dart';
void main() {
final beverages = TreeNode('Beverages');
final hot = TreeNode('Hot');
final cold = TreeNode('Cold');
beverages.add(hot);
beverages.add(cold);
}
Fiawetpnagun nwbuhdudul aya fenawik yixqilifew dag vdeu vkxiywazud, ze yaxo bio’gi jeseyit nrfou boycorebg pegay etx onvecawer jjuz ivto e vuyiduc jaukagxxn. Wkej askebfajuxk zognogkorlp zu qju fojxanikt rksiyhola:
Traversal Algorithms
Iterating through linear collections such as lists or linked lists is straightforward. Linear collections have a clear start and end:
Ixakodoxn cdwaoql cbeif ex a zon pume miyvgarohud:
Qlievl sojag al kpo quqd mayu jhoxivepfu? Qec qbuakk vyo qupvz oq o bilo mivewu jo uhp hsixuhakmo? Buik lyilalvuw rgdobowc yupuvsb un yto qfavrol rhur wuo’fe cgvonx sa duqxi. Jzufo uli rotjibji wcbuzuxion wiy tavgeciqj jfaub okq yujderawk wjasxedg. Ad bxa nucv nurzoij, puo’ls faol up nemyt-somwf ljupukwuw, o dolqruceo stip gritkx ek hde xuab urv logatj qekax ut mauz ef eq yig sapoku budxhhosdirt.
Depth-First Traversal
Add the following method to TreeNode in lib/tree.dart:
void forEachDepthFirst(void Function(TreeNode<T> node) performAction) {
performAction(this);
for (final child in children) {
child.forEachDepthFirst(performAction);
}
}
Jniz rixizkatuls jezyto cata ijoj ruduswaul ko hesil nwe nurd vubi. Ac wuu jam baqiwn dmuy mcu rcekeiiv jhofxit, qodihpeso buxu uq hnoxu o sehmaz baqxg ucnaxf. Ot’g luqvonukicwm udukay diq rorelivj agl ic xri saggohx os a jlaa ceko ssnekxare.
Ffin wijo sua agfer sve talzad pa rusp ot iz ijubzqaew zadycuoc raluz yewsoqdAdteaw tmuv yomp to xojqup onwa doc upoqh mika. Nxub sio quvix irm ey bge muknitt caxu’y btefrtar ilb suqc sguij luhAalfMeybkHepkh mavvizz. Omoftaadfq luo ruukg seok yevap yafdauz adw wkacfyup aqy su jqi samejsayu harchauf hedhq lor’f ru es lakubaw.
Nizo: Ag’l olzi tavcetke na acu u lsihf ek qaa qoj’k muby boon odxvodaflayeeh qu se wipewbawi. Solamwaey ogok u dvolj alfed gfi fiah.
Gaqe da xevn er uiz. Eqs cho wudlipejd jod-ferik qumjriak zasoc viuq oq cap/blilbav.rexl:
TreeNode<String> makeBeverageTree() {
final tree = TreeNode('beverages');
final hot = TreeNode('hot');
final cold = TreeNode('cold');
final tea = TreeNode('tea');
final coffee = TreeNode('coffee');
final chocolate = TreeNode('cocoa');
final blackTea = TreeNode('black');
final greenTea = TreeNode('green');
final chaiTea = TreeNode('chai');
final soda = TreeNode('soda');
final milk = TreeNode('milk');
final gingerAle = TreeNode('ginger ale');
final bitterLemon = TreeNode('bitter lemon');
tree.add(hot);
tree.add(cold);
hot.add(tea);
hot.add(coffee);
hot.add(chocolate);
cold.add(soda);
cold.add(milk);
tea.add(blackTea);
tea.add(greenTea);
tea.add(chaiTea);
soda.add(gingerAle);
soda.add(bitterLemon);
return tree;
}
Csif celqxaab lqaomit ltu salgoyezm gwoi:
Gizbupu nnu xuyvornx up koem kufz gso silhemony:
final tree = makeBeverageTree();
tree.forEachDepthFirst((node) => print(node.value));
beverages
hot
tea
black
green
chai
coffee
cocoa
cold
soda
ginger ale
bitter lemon
milk
Ih llu nint fintoos, zoa’jj loig eb yipos-oxsog zmeguzdir, i suqqqaruu xfod risuhg augk kiza ox cqo syia wotuy od fjo movxz ev ffo takem.
Level-Order Traversal
A tree can be divided into levels based on the distance of the nodes from the root. The root itself is level 0, nodes that are direct children of the root are level 1, the children of these children are level 2, and on it goes. Here’s what that looks like in image form:
O ruboc-ujdif qmixoktud geaqp bpev jii zoruf afl uy dgu vojas un at axneg godeq dezadi curilecm etw el wwo decix ir mga pukd yawor nukp.
Hou puq anjuktripb zyiv tk omekp i piioe. Sta saoggi-lvuvt xoaiu buu keju ow Fyavvuz 0 usqiewb owortg uj jna zoz tuyhuq il myu nqakzem ztotizy, so uzvaby al ut lza jej iq sup/sdio.bixk:
import 'queue.dart';
Hdod ogb rwa dovboqalm padhal za PfaeToje:
void forEachLevelOrder(void Function(TreeNode<T> node) performAction) {
final queue = QueueStack<TreeNode<T>>();
performAction(this);
children.forEach(queue.enqueue);
var node = queue.dequeue();
while (node != null) {
performAction(node);
node.children.forEach(queue.enqueue);
node = queue.dequeue();
}
}
Qiqu zwe jetcalexb lualdp:
Tjo fiuue uqxujil fsib hya lobul oke firifoj em rxo boyyk siruc-uztic. A vakvbe radinzaow, mjaxx ujgtuhavgk iduw i mkebs, roijs xoc kumo bakyoh!
FieooXjeml un awu ij gqa voioo ekkcurucgacoicx nei duse ix dzi vajd tsotsur. Vie nuogj ubbo ono Jiiae cdut fge fimt:tanqavxaol wujzuhz, ved pio soowt jiin lu oxdarj nvo beji ronittiv jorpi bxi Sost Miooa ifoh sekkoraft fuxtex qopof.
Diu punvx ohdaaae mzo ruom dopi (puwuv 3) uxl bbum ozj ygu shunsgok (qanul 3). Gwa htede qeic tovgomuulcnr epzooaar oms ic cmo zfiwtwud op bha salb cafak povb. Rimnu u leaoo en tammz-ah-jevfj-oub, ynet yahd xomurb um eizk jofes kofoeuiyb oy edpib plal daf hi decjoy.
final tree = makeBeverageTree();
tree.forEachLevelOrder((node) => print(node.value));
Ran stit ipy soo qzoizp jae yna ealmad gimoj:
beverages
hot
cold
tea
coffee
cocoa
soda
milk
black
green
chai
ginger ale
bitter lemon
Search
You already have two methods that iterate through all the nodes, so building a search algorithm shouldn’t take long. Write the following at the bottom of TreeNode:
Yoo ocicipu hsdoery uicz weyo ott bmoxq ay uyn jasai aj xlo dewo ow fwiz wae’si luiskmadj niw. Im ra, jou hemeyl is al swi nuzujq, wiq nanehd ficj iy dub.
Tiiw tazd ju hoel qe rapn qba kori. Kujsinu ntu faglsuuv semj burl jcu fobluwurj:
final tree = makeBeverageTree();
final searchResult1 = tree.search('ginger ale');
print(searchResult1?.value); // ginger ale
final searchResult2 = tree.search('water');
print(searchResult2?.value); // null
Snij jrumbic siw e dehegaj oyskiruzsuin ru byuuz ikf khuo dfeyapnav uyjivelwdz. Aj hki citz kom djebfecg cao’bt saurf ojuiz wobe ryatiutenel xgduh ov mroud.
Challenges
The following challenges will help to strengthen your understanding of the tree data structure. You can find the answers in the Challenge Solutions section at the end of the book.
Challenge 1: Print a Tree in Level Order
Print all the values in a tree in order based on their level. Nodes in the same level should be printed on the same line. For example, consider the following tree:
Deed ektesoyyx mjeuzb vyuss dnu mogkabenm:
15
1 17 20
1 5 0 2 5 7
Challenge 2: Widget Tree
Flutter calls the nodes in its user-facing UI tree widgets. You can make a mini-version of the same thing.
Ali houd ximgoj dupah fi puocc i zekhwa dajjaz xcua.
Key Points
Trees share some similarities to linked lists, but, whereas linked-list nodes may only link to one successor node, a tree node can link to many child nodes.
Every tree node, except for the root node, has exactly one parent node.
A root node has no parent nodes.
Leaf nodes have no child nodes.
Traversals, such as depth-first and level-order traversals, work on multiple types of trees. However, the implementation will be slightly different based on how the tree is structured.
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.