Given a Binary Search Tree, Traverse the tree in Preorder, Postorder, and inorder traversal.
Binary Search Tree
10
/ \
5 18
/ \ \
1 7 21
When you traverse a tree in root->left->right
fashion, it is called a preorder traversal. In the above example, the preorder traversal of the tree will be
10 5 1 7 18 21
Here, the traversal order will be left->right->root
. That is, left subtree is traversed first, then the the right subtree is traversed, and finally the root value is printed.
The postorder traversal of the above tree will be
1 7 5 21 20 18 10
Here, the traversal order will be left->root->right
. That is, left subtree is traversed first, then the root value is printed, and finally the right subtree is printed.
The postorder traversal of the above tree will be
1 5 7 10 18 21
The inorder traversal of a BST always returns value in a sorted order.
0 <= N <=1000;
N = Node value in a Binary Tree.
Click to reveal
Recursion is your best friend. The easiest way to solve this problem is to use recursion and finalize the order in which the recursion will happen. When do you think the value should be printed in each case?
Click to reveal
Pay attention to the printing order. For example, in preorder, you have to print the value first, then traverse the left subtree and finally the right subtree. How do you use recursion to accomplish this?