To validate a binary search tree (BST) in Java, you can use a recursive approach to check the following conditions for each node of the tree:
Here is an example of a recursive method that validates a BST in Java:
public boolean isValidBST(Node root) { if (root == null) { return true; } if (root.left != null && root.left.val >= root.val) { return false; } if (root.right != null && root.right.val <= root.val) { return false; } return isValidBST(root.left) && isValidBST(root.right); }
In this example, the isValidBST
method takes a Node
object representing the root of a BST and returns a boolean value indicating whether the BST is valid. The method checks the values of the left and right children of the root and the left and right subtrees of the root recursively. If any of the conditions is not met, the method returns false
. If all the conditions are met, the method returns true
.
You can use this method to validate a BST by calling it with the root of the tree. If the method returns true
, the BST is valid. If the method returns false
, the BST is not valid.
Note that this method assumes that the BST is implemented using a Node
class with val
, left
, and right
fields representing the value, left child, and right child of the node, respectively. You can adapt this method to work with other implementations of BSTs or with other data types and conditions.