Question about Depth First Search? Confused. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Question about Depth First Search? Confused.

I have been thinking about this question for a couple of days but can’t seem to have an answer. Why is that when you perform a depth-first search on a binary search tree, the keys are in sorted, increasing order

2nd Apr 2022, 11:23 PM
Annei ❤️
Annei ❤️ - avatar
4 Answers
+ 3
Indeed, that's why the method of traversal you are using here is also known as in-order traversal. As in a BST, every left subtree would have values less than the value of current node so it is guaranteed that while traversing left subtree first then current node and then right subtree, one would always get an increasing sequence.
3rd Apr 2022, 12:27 AM
Arsenic
Arsenic - avatar
+ 3
Annei ❤️ that depends on how exactly are you performing the depth first search. Depending on what you perform first when you reach certain node in tree, there are three ways to do so :- 1) preorder traversal : where you first visit current node then visit the left subtree and then right subtree. 2) postorder traversal: where you first visit left subtree, then right subtree and then visit the current node 3) inorder traversal: where you first visit left subtree, then visit current node and then right one. ( Due to the nature of BST, this one yields an increasing sequence as you would always be visiting nodes with lesser value than the current node first and then visit the node with higher values )
3rd Apr 2022, 12:43 AM
Arsenic
Arsenic - avatar
+ 2
but sorry, I have a question Arsenic 😅 Since were enqueuing, wouldn’t the value be going in a descreasing order?
3rd Apr 2022, 12:31 AM
Annei ❤️
Annei ❤️ - avatar
+ 1
Beautifully explained, Thank you!
3rd Apr 2022, 12:29 AM
Annei ❤️
Annei ❤️ - avatar