subtree of which is section as before we visit the left subtreewhich brings us to section then we visit the node for section with section finishedwe return to then we return to the book node and follow the same procedure for the code for writing tree traversals is surprisingly elegantlargely because the traversals are written recursively below we shows the python code for preorder traversal of binary tree you may wonderwhat is the best way to write an algorithm like preorder traversalshould it be function that simply uses tree as data structureor should it be method of the tree data structure itselfthe code below shows version of the preorder traversal written as an external function that takes binary tree as parameter the external function is particularly elegant because our base case is simply to check if the tree exists if the tree parameter is nonethen the function returns without taking any action def preorder(tree)if treeprint(tree get_root_val()preorder(tree get_left_child()preorder(tree get_right_child()we can also implement preorder as method of the binarytree class the code for implementing preorder as an internal method is shown below notice what happens when we move the code from internal to external in generalwe just replace tree with self howeverwe also need to modify the base case the internal method must check for the existence of the left and the right children before making the recursive call to preorder def preorder(self)print(self keyif self left_childself left preorder(if self right_childself right preorder(which of these two ways to implement preorder is bestthe answer is that implementing preorder as an external function is probably better in this case the reason is that you very rarely want to just traverse the tree in most cases you are going to want to accomplish something else while using one of the basic traversal patterns in factwe will see in the next example that the postorder traversal pattern follows very closely with the code we wrote earlier to evaluate parse tree therefore we will write the rest of the traversals as external functions the algorithm for the postorder traversalshown belowis nearly identical to preorder except that we move the call to print to the end of the function def postorder(tree)if tree !nonepostorder(tree get_left_child()postorder(tree get_right_child()print(tree get_root_val() tree traversals