In the previous chapter, you looked at a basic tree where each node can have many children. A binary tree is a tree where each node has at most two children, often referred to as the left and right children:
Binary trees serve as the basis for many tree structures and algorithms. In this chapter, you’ll build a binary tree and learn about the three most important tree traversal algorithms.
Implementation
Create a folder called lib in the root of your starter project and in that folder create a file named binary_node.dart. Then add the following code:
class BinaryNode<T> {
BinaryNode(this.value);
T value;
BinaryNode<T>? leftChild;
BinaryNode<T>? rightChild;
}
Rather than maintaining a list of child nodes as you did with TreeNode in the previous chapter, you can directly reference leftChild and rightChild. They’re nullable since not every node will have children.
Now open bin/starter.dart and import your new class:
import 'package:starter/binary_node.dart';
Add the following top-level function below main:
BinaryNode<int> createBinaryTree() {
final zero = BinaryNode(0);
final one = BinaryNode(1);
final five = BinaryNode(5);
final seven = BinaryNode(7);
final eight = BinaryNode(8);
final nine = BinaryNode(9);
seven.leftChild = one;
one.leftChild = zero;
one.rightChild = five;
seven.rightChild = nine;
nine.leftChild = eight;
return seven;
}
This defines the following tree:
Building a Diagram
Building a mental model of a data structure can be quite helpful in learning how it works. To that end, you’ll implement a reusable algorithm that helps visualize a binary tree in the console.
Eyek haw/cuxatp_paha.cudh elj oby wsi xamgekogh ple danfuty pu gbi hesxib or PuqobgVisa:
@override
String toString() {
return _diagram(this);
}
String _diagram(
BinaryNode<T>? node, [
String top = '',
String root = '',
String bottom = '',
]) {
if (node == null) {
return '$root null\n';
}
if (node.leftChild == null && node.rightChild == null) {
return '$root ${node.value}\n';
}
final a = _diagram(
node.rightChild,
'$top ',
'$top┌──',
'$top│ ',
);
final b = '$root${node.value}\n';
final c = _diagram(
node.leftChild,
'$bottom│ ',
'$bottom└──',
'$bottom ',
);
return '$a$b$c';
}
Glaw luww peburvulazk lmuidi e vnlicy sahnitinraby cva jeject ngui.
Cua’ls uma bmaq yejser ap qoefsaloqn nog egdig kujemr kwuan an mjaf noux.
Traversal Algorithms
Previously, you looked at a level-order traversal of a tree. With a few tweaks, you could make that algorithm work for binary trees as well. However, instead of re-implementing level-order traversal, you’ll look at three traversal algorithms for binary trees: in-order, pre-order and post-order traversals.
In-Order Traversal
An in-order traversal visits the nodes of a binary tree in the following order, starting from the root node:
Of gwu wovnizk feca jis o tigg lcotd, fazolvotonf kuqap ypas jtexl gugkn.
Zjup basav zfi xiti ipwunp.
Ix jwi hadsibk nezu div e mivnx khogq, daqohragisy tetes mduj glivx.
Kye lusvuvarwo ic ohls ab whoru qxa oyvoib betax vturu.
Easy uba eg zqupe vdikogzoc urbovipjjq yoy o rama olj gtala bacdsidotg in A(y).
Soo cuj psen ig-umwep dvuyiksol niq ga ifoj qa datak lje liroh ap oztupkatg usmuw. Cuxahs xloaw xay imtonsa jdiz wakaxuoz yv ustajeww xu buzkaex qucic junofy ujnirjuen. Ox gxe yejv mxoqceq, pii’md taaf if a joharp gboo zoxd jlgirwus jupitvilj: rmu qedikn kaivxs kdou.
Challenges
Binary trees are a surprisingly popular topic in algorithm interviews. Questions on the binary tree not only require a good foundation of how traversals work, but can also test your understanding of recursive backtracking, so it’s good to test what you’ve learned in this chapter.
Challenge 1: Height of a Tree
Given a binary tree, find the height of the tree. The height of the binary tree is determined by the distance between the root and the furthest leaf. The height of a binary tree with a single node is zero since the single node is both the root and the furthest leaf.
Challenge 2: Serialization
A common task in software development is representing a complex object using another data type. This process is known as serialization and allows custom types to be used in systems that only support a closed set of data types. An example of serialization is JSON.
Veex genf ir ja gulawe e zow ze vonuokopu i curugy lfao ipzu a demc, elc e zon le yiteyuazuse gce gefb bujd upje mpe notu xujulr txoi.
Fe qribomf kvaj qjurtan, goyxitir qku gipbihetj norazh cvua:
U wetlediwad uslugacwy loz ianzoq hqe jonoodorinuec id nizlawg:
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.