Advertisement
Guest User

Untitled

a guest
Mar 6th, 2015
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. The first thing I did while working on this practical is implementing a binary search tree in treenode.c. It was useful to have treenode.h supplied as part of the specification, since it explicitly stated which features of the tree must be implemented. Writing treenode.c gave me a chance to practice using the malloc function, which is needed to dynamically allocate memory for everything stored in the tree. After each malloc call, I added an assert statement to check that the allocated pointer was not NULL. I did this to ensure that the program exits if it runs out of memory and is no-longer able to allocate the required resources during runtime. Dealing with trees, I had two ways of navigating nodes - iteratively and recursively. In functions which don’t backtrack, such as ``query’’ and ``insert’’, I chose to navigate the tree iteratively to avoid having to write helper functions. Other functions like ``printTree’’ and ``freeTree’’ are required to backtrack in order to visit every node. I chose to write these functions recursively using helper methods ``printNode’’ and ``freeNodeWithChildren’’, since an iterative implementation would have required a stack - which is not included in the standard library. Additionally, I implemented a method for calling a function on each node of the tree (extension), called ``reduce’’. This function takes a TreeBase pointer and a ``reduce_fn’’ - a function that takes two void pointers and returns an int. ``reduce’’ calls ``reduce_fn’’ on every node in the tree and sums the return values with each other and 0. This allowed me to implement some extensions in part B.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement