Skip to content

Instantly share code, notes, and snippets.

@spotco
Last active December 14, 2015 06:48
Show Gist options
  • Save spotco/5045097 to your computer and use it in GitHub Desktop.
Save spotco/5045097 to your computer and use it in GitHub Desktop.
isSorted(root,Integer.MIN_VALUE,Integer.MAX_VALUE);
public static boolean isSorted(Node cur, int min, int max) {
if (cur==null) {
return true;
} else if (cur.val < min || cur.val > max) {
return false;
} else {
boolean sorted = true;
if (cur.left != null && cur.left.val > cur.val) {
sorted = false;
}
if (cur.right != null && cur.right.val < cur.val) {
sorted = false;
}
return sorted && isSorted(cur.left,min,cur.val) && isSorted(cur.right,cur.val,max);
}
}
/**
* The second base case is for the case
* 5
* 4 7
* 3 6 6 8
*
* Which would pass without it, but is technically incorrect based on the definition.
**/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment