Sunday, March 8, 2015

Slog#6. "Binary Tree, Binary Search Tree"

This week, we focused on class binary tree (BT) and binary search tree (BST). Unlike class Tree, which may have unlimited number of children, BT and BST can only have maximum of two children per parent node. Due to limited number of children each node can have, I thought BT and BST would be somewhat simpler to deal with. However, as the blogger at http://akcolter.blogspot.ca/ mentioned, I found this week’s materials significantly more complicated than what we have learned thus far in this course.
Though I thought I had a clear understanding of recursive methods, writing BT and BST methods with recursion was much more challenging. The most challenging part was to understand recursion that appeared in __str__ method of BT and BST. At first, I did not even understand why it was recursive methods. Also, I did not understand how __str__ method was able to put a new line character after right_tree when right_tree statement did not contain new line character. After drawing lots of diagrams of different cases, I learned that right_tree and left_tree variables also involve recursion by calling __str__ method on them, if they existed. Therefore, return statement of __str__ method is being called on each side of tree and that is where new line character is coming from. For instance, when __str__ is called on a right_tree that has no children, its own left and right tree does not exists and it will only return '{}{}\n'.format(indent, str(self.data)), where self.data refers to the “root” of the right_tree, rather than the root of the whole tree.
To improve my understanding better, I also worked on the exercise on writing recursive evaluate method. Here, I used recursion to find nodes whose data is float and created a string of "b.left" + "b.data" + "b.right" and called "eval" on this string which returns the result of this expression. This will continue until every node in BST is evaluated and returns one single float. 

No comments:

Post a Comment