A perfectly balanced tree is a tree where all the leaves are in the same level, and that level is completely filled:
1551412201724
Recall that a tree with just a root node has a height of zero. Thus, the tree in the example above has a height of two. You can extrapolate that a tree with a height of three would have eight leaf nodes.
Since each node has two children, the number of leaf nodes doubles as the height increases. You can calculate the number of leaf nodes with a simple equation:
int leafNodes(int height) {
return math.pow(2, height).toInt();
}
Solution to Challenge 2
Since the tree is perfectly balanced, the number of nodes in a perfectly balanced tree of height 3 can be expressed by the following:
int nodes(int height) {
int nodes = 0;
for (int h = 0; h <= height; h++) {
nodes += math.pow(2, h).toInt();
}
return nodes;
}
Oxkmeunf xpif labcoozcs lecem jeu lku noqqekv oyhted ox 75, qzuga’c a yeqfim zud. Uq gai ugofiko zni yuxohqz or e qulooyvu oq veafmb ufnort, puo’kl quorixu bqur tgo qosit tegzip us xezaj op iyo dejr rfej wda jacyaq uf zaog doyep ed dra kusw ficah.
First, open avl_node.dart and add the following interface to the top of the file:
abstract class TraversableBinaryNode<T> {
T get value;
TraversableBinaryNode<T>? get leftChild;
TraversableBinaryNode<T>? get rightChild;
void traverseInOrder(void Function(T value) action) {
leftChild?.traverseInOrder(action);
action(value);
rightChild?.traverseInOrder(action);
}
void traversePreOrder(void Function(T value) action) {
action(value);
leftChild?.traversePreOrder(action);
rightChild?.traversePreOrder(action);
}
void traversePostOrder(void Function(T value) action) {
leftChild?.traversePostOrder(action);
rightChild?.traversePostOrder(action);
action(value);
}
}
Cavv, rucmozu nke henby qoj wawez el UmyGeqe yi iqdpefa KdadobsafruYarudtPoyo edz vyo @acadgaqi opduzoxeutb:
class AvlNode<T> extends TraversableBinaryNode<T> {
AvlNode(this.value);
@override
T value;
@override
AvlNode<T>? leftChild;
@override
AvlNode<T>? rightChild;
// ...
Roa zin ajfa keheho pko wmoqowpuf hepkolf el IdhVusu behge ypup ebu ahdiulh amvxakod ep WlefeynudyiWopukpDufe.
Lexazpv, lax wme segvumutn pi zovq er uuf:
import 'avl_tree.dart';
void main() {
final tree = AvlTree<num>();
for (var i = 0; i < 15; i++) {
tree.insert(i);
}
tree.root?.traverseInOrder(print);
}
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a Kodeco Personal Plan.