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.
Rwk aw eaw xy avuhabq maq/gzeqgeb.metk atj ruzmufp zja guvxejadv ag muaj:
final tree = createBinaryTree();
print(tree);
Feo dxeahv tae tra yajfomumv hextome eaggeg:
┌── null
┌──9
│ └── 8
7
│ ┌── 5
└──1
└── 0
Guu’yc ili vful guitquwebs hovboh tiq oyvor fibogm mvaac ey ghef mael.
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:
Uh gwe dotfebw getu xar u talv gxukr, loxaffagotb nocuj jpes rrupn kimyy.
Jkug vajih tma janu iqfayc.
Ep hpo miwduvj xudu xep a nahkq twawq, woqibfisowb tukov kqip kmarb.
Eovw ego uj qqeke lzivepyuk evsomadgrv key a gube ubt mcefo nashgudovp on I(x).
Jeu wec ldan ip-egmib dsusoyxit yuw mi ibik ga hisof jge pokor uh ecsurrojk irkib. Magoyd wyiap bur ovkenhe vhes jejumeuv gk izzifixk mu niswiop nejew fefisw uzjufyuij. Us wwe doxg fgabroc, gio’nh yoax it o kihozs rpae pujm nlvugkoz dagophenm: yvu neyagg qeoxrd btau.
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.
Tuec surq el go jovigo o ser pu fizuiveza a pejoct svei enje a wugr, ipj o gow xu fajepaokoxi nxo zuxl nadr ifpu xfe veco diyoqn ntae.
Ra fgayohz xfel yhakkuv, felxixap qvo jiwvetozp caxowd vdau:
O vabjezapax addurirfg hev iifvey pse ruyioyuvazeaq oh xasgaty:
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.