patternjavaMinor
Testing to see if tree is BST
Viewed 0 times
bsttestingtreesee
Problem
I found a function online that tests if a tree is a binary search tree:
I don't quite understand why
Here is the code for both functions:
I made some edits to the
I am wondering if there is any sort of logic I am missing.
private boolean isBST(Node node) {
if (node==null) return(true);
// do the subtrees contain values that do not
// agree with the node?
if (node.left!=null && maxValue(node.left) > node.data) return(false);
if (node.right!=null && minValue(node.right) <= node.data) return(false);
// check that the subtrees themselves are ok
return( isBST(node.left) && isBST(node.right) );
}I don't quite understand why
maxValue and minValue are being used.Here is the code for both functions:
private int minValue(Node node) {
Node current = node;
while (current.left != null) {
current = current.left;
}
return(current.data);
}
private int maxValue(Node node) {
Node current = node;
while (current.right != null) {
current = current.right;
}
return(current.data);
}I made some edits to the
isBST1 in my own way, but I'm not sure if there are any flaws in it or not. static boolean isBST1(BinaryTreeNode root) {
if (root == null) {
return true;
}
if (root.left != null && root.left.value > root.value) {
return false;
}
if (root.right != null && root.right.value < root.value) {
return false;
}
return isBST1(root.left) && isBST1(root.right);
}I am wondering if there is any sort of logic I am missing.
Solution
Here's a simple tree that can demonstrate a couple things:
minValue and maxValue are written so that the algorithm can catch the 6 that is out of place. And it seems like even the original versions of those functions are not doing that right. Your new algorithm will check the left value (3) and say it's okay, then check the 3-1-6 subtree and also say it's okay, when there's obviously a 6 that is on the left side and that is bigger than the root.
Your new algorithm, however, is broken in the same way as the old algorithm that uses minValue and maxValue is broken, so you translated code with functions into code with no functions "correctly" (didn't change anything).
5
/ \
3 7
/ \ \
1 6 8minValue and maxValue are written so that the algorithm can catch the 6 that is out of place. And it seems like even the original versions of those functions are not doing that right. Your new algorithm will check the left value (3) and say it's okay, then check the 3-1-6 subtree and also say it's okay, when there's obviously a 6 that is on the left side and that is bigger than the root.
Your new algorithm, however, is broken in the same way as the old algorithm that uses minValue and maxValue is broken, so you translated code with functions into code with no functions "correctly" (didn't change anything).
Code Snippets
5
/ \
3 7
/ \ \
1 6 8Context
StackExchange Code Review Q#39500, answer score: 5
Revisions (0)
No revisions yet.