Over the previous two weeks, we have been working on a new data structure: trees. These, vaguely similar to real-world trees, have a root and "children". Trees are an important structure to know because many of its methods and functions which use a tree as a parameter require recursion, something we've been getting more experienced with.
First, we started with the basics, defining what a tree was and some of its attributes, such as the value of the root node, and the nodes which make up its children; a node with no children is considered a "leaf" while the rest are considered internal nodes. A general tree has a certain arity or branching factor, determined by the maximum amount of children that one of its nodes has; trees also have depth and height, determined by the paths from the root node to the last child. As the week went on, we started discussing and implementing some methods for the general tree. This included leaf-count, which as explained above counts the number of nodes which have no children. Then, other methods were written to determine height, internal nodes, order of the nodes in a tree and some more properties. While implementing the methods, it was apparent that they used the general recursion structure, a condition which checks for the base case, and then a general case where recursion is to be used.
Another more specific type of tree that we learned and worked with in week 8 was binary trees. These are trees in which the branching factor is 2, and every non-leaf node has exactly two children. Similar to the general tree, we implemented some methods and functions which used recursion. We also worked on different ways to order and search through the nodes in binary trees, which would then make it easier to understand and implement the same for the general tree. One order method checks the left node, then the parent and lastly the right node, while another checks the root node, then its children, its grandchildren, etc. Lastly, we saw a special type of binary tree: a binary search tree (BST), a tree where the value of the right child is always greater than its parent's, and the left child's value is less than the parent's. The BST makes searching through the tree substantially faster than the general type; for example, to check if a value was in the tree, it checks whether the value is contained in each node, and accordingly checks either the left or the right child depending on whether this value is less than or greater to the parent, which is greatly efficient.
Next week is the second midterm in this course. Surely a lot of recursion is to be expected, as well as going back to review data types like linked lists. I wish the best of luck to my fellow students, and hopefully this time we will have less constricting time limitations.
No comments:
Post a Comment