in DS edited by
37,298 views
48 votes
48 votes

A binary search tree contains the value $1, 2, 3, 4, 5, 6, 7, 8$. The tree is traversed in pre-order and the values are printed out. Which of the following sequences is a valid output?

  1. $5 \ 3 \ 1 \ 2 \ 4 \ 7 \ 8 \ 6$
  2. $5 \ 3 \ 1 \ 2 \ 6 \ 4 \ 8 \ 7$
  3. $5 \ 3 \ 2 \ 4 \ 1 \ 6 \ 7 \ 8$
  4. $5 \ 3 \ 1 \ 2 \ 4 \ 7 \ 6 \ 8$
in DS edited by
37.3k views

1 comment

Note here in all options 5 is the first one traversed hence it is root. So we have now two sets of vertices { 1,2 3, 4} on left subtree and {6, 7, 8 } on right subtree.

Proceed in this way using option elimination you will get D as valid answer.
5
5

7 Answers

65 votes
65 votes
Best answer

Note: PreOrder means Root-Left-Right Traversal of tree.

By Option Elimination:-

B. False. Because $5$ is root so in preorder sequence first $5$ elements must contain $1$ to $5$ But $6$ comes here. So false.

So, now common things in option A,C,D is $5,3$ means $5$ root then LHS subtree root is $3$ . now $3$ s LHS is $1,2$ so they should come first rather than $4$. So option C is False.

Now Check for Option A,D.

Root $5$'s RHS is $6,7,8$ now as per Option A,D $7$ is Root so $6$ should be Left and $8$ should be Right so pre order for Right sub tree is $7,6,8$ (Root-L-R). This satisfies option D.

Correct Answer: $D$

edited by

4 Comments

@Swati Ranuiyar Preorder traversal of your tree prints 4 before 6, which is wrong.
0
0
in this tree the 4 come first and 6 will come after 4 check your pre ordering once again
0
0
hats off your explanation, thanks you.
0
0
18 votes
18 votes

Answer: D

The tree is:

4 Comments

how did you draw the above tree isnt it wrong?

try here https://www.cs.usfca.edu/~galles/visualization/AVLtree.html

0
0
@manojk ; your argument is contradictory
0
0

@SrijaRajesh0909 it comes with practise

0
0
7 votes
7 votes
The best thing is to draw the tree and see whether it is following preorder rule or not just like

A) when we traverse in preorder after making tree, 6 comes before 8. so false

B) when we traverse in preorder after making tree, 4 comes before 6. so false

C) when we traverse in preorder after making tree, 1 comes before 4. so false

D) it is right sequence it follow preorder rule.

2 Comments

preorder and inorder last node shoulde be same..

eliminate Option A & B.

take inorder & preorder with  C & D option.

Inorder in BST always sorted..draw tree option C & D and check which is valid
0
0
Don't you think first node of preorder and last node of post order should be same but not the inorder?
0
0
2 votes
2 votes
answer D

1 comment

We can also construct bst for each option and find its preorder we will see that option d is right
4
4
Answer:

Related questions