I wrote a solution for checking the validity of the binary search tree using LinkedList and it's proving wrong information about the validity. I checked with a valid BST and it returns that the tree is not valid. The code is as following,
public static boolean isValidBST_( Node root ){
boolean bol = false;
LinkedList<Node> queue = new LinkedList<Node>();
queue.add(root);
while( !queue.isEmpty() ){
Node cur = queue.poll();
if ( ( cur.left != null && cur.data > cur.left.data ) || (cur.right != null && cur.data < cur.right.data ) ){
return bol;
}
if ( cur.left != null ){
queue.offer(cur.left);
}
if ( cur.right != null ){
queue.offer(cur.right);
}
} // WHILE
if (queue.isEmpty() ){
bol = true;
}
return bol;
}
How can I improve the code ?
I make the call from main as following,
public static void main (String[] args ){
Node root = new Node(5);
root.left = new Node(3);
root.right = new Node(7);
root.left.left = new Node(1);
root.left.right = new Node(4);
root.right.left = new Node(6);
root.right.right = new Node(9);
System.out.println("Does the inserted BST is valid ? Answer: " + isValidBST_(root));
}
LinkedList"queue"?