I need to write a method to determine if a tree is a binary search tree. Here\'s
ID: 3630187 • Letter: I
Question
I need to write a method to determine if a tree is a binary search tree.Here's what I wrote, but it crashes because of NullPointerException or runs forever. Can you help me improve it? Thanks!
public static boolean check(TreeNode t)
{
boolean a=checkForBinary(t.leftChild);
boolean b=checkForBinary(t.rightChild);
if(a&&b)
{
return true;
}
return false;
}
public static boolean checkForBinary(TreeNode t)
{
boolean binaryTree=false;
while(t!=null)
{
if (t.leftChild!=null)
{
if (t.item<t.leftChild.item)
{
binaryTree=false;
return binaryTree;
}
else
{
checkForBinary(t.leftChild);
}
binaryTree=true;
}
else if (t.rightChild!=null)
{
checkForBinary(t.rightChild);
}
}
return binaryTree;
}
Explanation / Answer
void check(struct Tree *node)
{
static int lastData = min;
if(node == NULL)
return;
check(node->left);
if(lastData < node->data)
lastData = node->data;
else {
cout << "It's not a binary search tree" ;
return;
}
check(node->right);
return;
}