You are viewing a single comment's thread. Return to all comments →
Would not work in all cases.
Consider this tree: root.data = 2, root.left.data = 1, root.left.right.data = 3
1 is on the left of 2 and indeed smaller than 2. 3 is on the right of 1 and is indeed larger than 1. However, you can see that this is not a proper binary search tree since 3 is inside the left sub-tree of 2.
jongray93's solution returns false on your tree. In the first iteration, on the root node, the code will check the last condition:
return check(n.left, min, n.data)
&& check(n.right, n.data, max);
The right node will return true because n.right is NULL, and the left will continue searching down the three, with the max value updated to 2 (root's data value). Therefore any node whose data is greater than 2 (your last node) will return false.