This week, we finished off learning about binary trees which are basically trees but with a limit of two children per node. This may sound as if it were limiting the power of trees but in actuality, it provides us with some useful tools such as being able to check whether a value is contained in the tree without having to visit every node/leaf.
The idea for binary trees is that the left child of the parent node has a value less than the parent node itself whereas the right child of the parent node has a value greater than the parent node itself. Thus in the scenario:
Parent node value: 15
Left child value: 10
Right child value: 20
if we were looking to see if 17 was in the tree, we already know it isn't contained in the left child since 17 > 15 which implies it is in the right child tree if it exists. This effectively eliminates a lot of extra work for the computer and reduces the runtime of the program. In the scenario where the value we are looking for is in fact 15:
1) Does this node have a value?: YES
2) Is 15 < value of the current node?: NO
3) Is 15 > value of the current node?: NO
4) Thus, it implies that the value of the node it is on is in fact 15.
However, accomplishing this task requires quite a bit of mastery in recursion since we must recursively call the tree in order to travel through the nodes.
We also started talking about linked lists. One of the key concepts I found to be important would be how much the order of the code matters. For example when we append an element to a linked list, we need to change:
- last node
- former last node
- back
- size
- possibly front
If we change any of these in the wrong order then a syntax or maybe even a logic error would occur.
For example, when we switch the values of two variables we can't simply assign one to the other.
a = 5
b = 10
If I wanted to interchange the values of "a" and "b" I can't simply say a = b and b = a since the following would occur:
>>> a = b
>>> b = a
>>> print(a)
>>> 10
>>> print(b)
>>> 10
The value of "a" was changed so saying b = a does not give "b" the value 5 anymore. This situation is quite relatable to linked lists.
Thus, when working with linked lists, we must always keep in mind what we need to change first and how one line of code will affect the other
Good example of Linked list. I learned how to do them after reading this post.
ReplyDelete