Over the past two weeks CSC148 has focused on binary trees. Binary trees are a type of tree that have an arity of 2. This means that tree traversals can be reduced to a single if operation at each inner node. While there are certainly a couple places you might want to use a binary tree, the most obvious and interesting place is for storing data that has a useful inequality operation, like an int (7 < 8) or a str (‘abc’ < ‘dz’). Why? Because when set up correctly in a binary search tree, searching for the data in the tree is much faster than other data structures. To understand, we simply have to look at how we’d search for an object in other collection types.
In a list, set, or dictionary (if we’re looking for a value, not a key), the simplest way is to check every object until we find a match. This has a worst case where we’ll have to make a comparison for every single object in the collection. This is linear time and not efficient.
With a randomly assembled binary tree, the simplest way to search for an object is the same, but if the tree is created in such a way that a node’s left child has a lesser value and it’s right child has a greater value, then a comparison only has to be made for every node from the root to the desired value. Of course, if we’re searching for the least object in a set, and the root is the greatest object, then every node will be checked. However, if the tree is balanced – has the least possible height – then the worst-case scenario is one where only log base 2 nodes are checked. This is logarithmic time and is much more efficient.
A similar search can be done on a sorted list as well, which is partially why finding an efficient sorting algorithm is important.
No comments:
Post a Comment