Consider a binary search tree (BST). Why does performing an inorder traversal on it produce the nodes in sorted order?
Think about how the BST property relates to the order of visiting nodes.
Inorder traversal visits the left subtree first, then the root, then the right subtree. Since in a BST all left subtree nodes are smaller than the root and all right subtree nodes are larger, this order naturally produces sorted values.
Given the BST below, what is the inorder traversal output?
5
/ \
3 7
/ \ \
2 4 8
Remember inorder is left, root, right.
Inorder traversal visits nodes in left-root-right order. For this tree, it visits 2, then 3, then 4, then 5, then 7, then 8.
If you perform an inorder traversal on a binary tree that is NOT a binary search tree, what can you say about the output?
Think about what property makes inorder traversal produce sorted output.
Inorder traversal visits nodes in left-root-right order regardless of tree type. Only BSTs guarantee that left subtree nodes are smaller and right subtree nodes are larger, so only then is the output sorted.
Given a BST, how does the output of inorder traversal compare to preorder traversal?
Recall the order each traversal visits nodes.
Inorder traversal visits left-root-right, producing sorted output on BSTs. Preorder visits root-left-right, which does not guarantee sorted order.
Suppose a binary tree has nodes arranged so that some left child is greater than its parent. Why does inorder traversal fail to produce sorted output in this case?
Think about what the BST property guarantees about node values.
Inorder traversal visits left subtree, then root, then right subtree. If left child is greater than parent, the order left-root-right does not produce sorted values because the BST property is broken.