Reputation:
Usually we traverse the Binary search tree either in order ,preorder or post order.But what happens when we traverse the Binary Search Tree in the following recursive order From Right - Root -Left?
Suppose if i store the values in an array and whether its time complexity increases when we do the traversal in this order when compared to preorder traversal.
Upvotes: 1
Views: 2333
Reputation: 41145
Let's use an example binary search tree:
5
/ \
3 7
/ \ / \
2 4 6 8
In-order traversal (Left tree, root, right tree)
2 3 4 5 6 7 8
How did we get that?
Pseudo code:
InorderTraversal(root)
{
if root is not null:
InorderTraversal(root.left)
print root
InorderTraversal(root.right)
}
Let's play computer on our tree
Right root left traversal
8 7 6 5 4 3 2
Pseudo code:
RightRootLeftTraversal(root)
{
if root is not null:
RightRootLeftTraversal(root.right)
print root
RightRootLeftTraversal(root.left)
}
As you can see, this is in exactly the opposite order as an in-order traversal. On a binary search tree, we will get a reverse-ordered traversal.
The number of operations is identical to a preorder traversal, which is O(n) because we visit every node one time.
Upvotes: 1