"Of all the trees we could've hit, we had to get one that hits back." - J.K. Rowling
That is exactly how I felt about exercise 4 for CSC148. Exercise 4 a) was not a difficult task, so long you followed the professor's advice about "working it out on paper before programming". It took me a few hours before it hit me while I was on the subway. I had found the task of creating a tree from preordered and inordered lists difficult until I realized the simple fact that all of the hints required were ALREADY written on the paper (silly me for spending 2 hours figuring them out myself), and that trees consist of subtrees (the main reason recursion is so useful). Implementing the recursion I found, was a breeze contrary to my usual difficulty with it.
Exercise 4. b) was much easier to implement since we have already worked out so many list comprehensions at this point (one for max depth and one for sum of a list) so I found it wasn't as challenging as the first. I wasn't certain whether or not a list like : [1, [], None] would be tested but I handled that case as well just in case.
My only question now is why the hint that an empty tree has a depth of -1 is useful...
The thing about -1 is that you can calculate the depth of leaves the same as all other nodes: the max of the depth of their children (-1), plus 1, or 0.
ReplyDeleteIt looks as though you've got a good grasp of recursion.
That makes sense, thank you for the reply!
Delete