Does a sorted sequence from in-order traversal imply a binary tree is a BST?

73 Views Asked by At

An in-order traversal of a binary search tree (BST) produces a sorted sequence. I wonder, if we perform an in-order traversal of a binary tree and obtain a sorted sequence, does that imply that the tree was a BST? (Is it a necessary and sufficient condition?)

I was looking for an algorithm to check if a given binary tree is a BST or not with the best time complexity. One of the solutions here suggested to do an in-order traversal and verify if the sequence is sorted. But I don't understand why this is a necessary and sufficient condition. I need a clear and rigorous proof.

I appreciate any help!

1

There are 1 best solutions below

3
Gustav Woltmann On

An in-order traversal of a binary search tree (BST) does indeed produce a sorted sequence. However, it's important to note that while a sorted sequence obtained from an in-order traversal is a necessary condition for the tree to be a BST, it is not a sufficient condition.

Necessary Condition: If the in-order traversal of a binary tree produces a sorted sequence, it means that the tree has the binary search tree property. In a BST, for any given node, all nodes in its left subtree have values less than the node, and all nodes in its right subtree have values greater than the node. Therefore, traversing the tree in an in-order fashion will visit nodes in ascending order.

Insufficient Condition: However, the converse is not necessarily true. A binary tree may produce a sorted sequence during an in-order traversal without being a BST. This situation can occur if the tree has a structure that aligns with the sorted order, even if it doesn't strictly adhere to the BST property.

Example: Consider the following binary tree:

    2
   / \
  1   3
 / \
4   5

The in-order traversal of this tree produces the sequence [4, 1, 5, 2, 3], which is sorted. However, this tree is not a BST because the left subtree of the root contains a node (1) greater than the root (2).

Proof Sketch: To rigorously prove this, you can use a counterexample approach. Construct binary trees that are not BSTs but produce sorted sequences during in-order traversals. By demonstrating these counterexamples, you show that the sorted sequence from an in-order traversal is not a sufficient condition for a tree to be a BST.