Reputation: 279
I came upon this question on a "Practice Final" that I am using to study for the real final:
I can't think of why this method wouldn't work. The logic seems fine. A BST is only a BST if each left < parent < right, which is precisely what this method checks, recursively.
Any hints would be appreciated!
Upvotes: 2
Views: 107
Reputation: 500903
Duplicate values aside, the definition of a binary search tree requires that:
The left sub-tree contains only nodes with keys less than the parent node; the right sub-tree contains only nodes with keys greater than the parent node.
The code in your question does not check that. Consider the following tree:
2
/
1
\
3
This would pass the test, but isn't a valid BST: for this to be a BST, 3
has to be be in the right subtree of 2
.
See https://stackoverflow.com/a/759851/367273 for an example of a correct implementation.
Upvotes: 3