Given a Binary Search Tree, Traverse the tree in Preorder, Postorder, and inorder traversal.
The traversal mechanism are simple and straightforward. We are going to take a recursive approach and print the traversals accordingly.
The base case in each of the traversing mechanisms will be when there is no tree to traverse, i.e. tree === null
. This ensures that we are at the leaf nodes (since we are going to backtrack from here and going to proceed with the subsequent calls).
Since the traversal has to be in a root-left-right
manner, we are going to print the root value first.
!tree
- return.root
value.root.left
root.right
Since the traversal has to be in a left-right-root
manner, we are going to print the root value first.
!tree
- return.root.left
root.right
root
valueSince the traversal has to be in a left-root-right
manner, we are going to print the root value first.
!tree
- return.root.left
root
value.root.right
In all the above mentioned traversal methods, it's the order in which the values are printed. The printing and recursion order will determine which traversing mechanism is applied in place.
O(n)
- In all the cases since we are going to visit each node atleast once.