Pre-order traversal and prefix notation

Pre-order tree traversal works as follows. First of all, we check if the current node is null or empty. If it is not empty, we traverse the tree. The pre-order tree traversal works as follows:

  1. We start traversing with the root node
  2. Next, we traverse the left sub-tree and call the preorder function with the left sub-tree recursively
  3. Next, we visit the right sub-tree and call the preorder function with the right sub-tree recursively

So, to traverse a tree in pre-order mode, we visit the tree in the order of root node, the left sub-tree, and the right sub-tree node. 

Consider the following example tree to understand pre-order traversal:

In the preceding example of a binary tree, first, we visit root node A. Next, we go to the left sub-tree of root node A. The left sub-tree of node A has node B as the root, so we visit this root node and the go to the left sub-tree of root node B, that is, node D. We then visit node D and go to the left sub-tree of root node D, and then we visit the left child, G, which is the sub-tree of root node D. Next, we visit the right child of the sub-tree with root node D, that is, node H. Next, we visit the right child of the sub-tree with root node B, that is, node E. So, in this manner, we have visited root node A and the left sub-tree with root node A. Now, we will visit the right sub-tree of root node A. Here, we visit the root node C, and then we go to the left sub-tree with root node C, which is null, so next, we visit the right child of node C, that is, node F.

The pre-order traversal for this example tree would be A-B-D-G-H-E-C-F.

The recursive function for pre-order tree traversal is as follows:

    def preorder(self, root_node): 
current = root_node
if current is None:
return
print(current.data)
self.preorder(current.left_child)
self.preorder(current.right_child)

Prefix notation is commonly referred to as Polish notation. In this notation, the operator comes before its operands. Prefix notation is well known to LISP programmers. For example, the arithmetic expression to add two numbers, 3 and 4, would be shown as + 3 4. Since there is no ambiguity of precedence, parentheses are not required: * + 4 5 - 5 3.

Let's consider another example, that is, the (3 +4) * 5 . This can also be represented as * (+ 3 4) 5 in prefix notation. 

The pre-order traversal of an expression tree results in the prefix notation of the arithmetic expression. For example, consider the following expression tree:

The preorder traversal of the preceding tree will give the expression in prefix notation as +- 8 3 3.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset