Книга: A Common-Sense Guide to Data Structures and Algorithms in Python, Volume 1
Назад: Chapter 15: Speeding Up All the Things with Binary Search Trees
Дальше: Binary Search Trees

Trees

You were introduced to node-based data structures in the previous chapter with linked lists. In a classic linked list, each node contains a link that connects the node to a single other node. A tree is also a node-based data structure, but within a tree each node can have links to multiple nodes.

Here is a visualization of a simple tree:

/books/45079/OEBPS/binary_trees/bst_1.png

In this example, each node has links that lead to two other nodes. For the sake of simplicity, we can represent this tree visually without showing all the memory addresses:

/books/45079/OEBPS/binary_trees/bst_2.png

Trees come with their own unique nomenclature:

/books/45079/OEBPS/binary_trees/bst_3.png

For instance, the preceding tree is said to be perfectly balanced. If you look at each node, its two subtrees have the same number of nodes. The root node (“j”) has two subtrees, which each contain three nodes. You’ll see that the same is also true for every node in the tree. For example, the “m” node also has two subtrees where the two subtrees each contain one node.

The following tree, on the other hand, is imbalanced:

/books/45079/OEBPS/binary_trees/imbalanced_tree.png

As you can see, the root’s right subtree contains more nodes than its left subtree, causing an imbalance.

Назад: Chapter 15: Speeding Up All the Things with Binary Search Trees
Дальше: Binary Search Trees