How to search in binary sort tree in Java
To search for a specific value in a binary search tree (BST), you can use a recursive or iterative approach.
In a recursive approach, you can define a search function that takes as input the root node of the BST and the value that you want to search for. The function can then traverse the BST in a depth-first manner, comparing the value of each node to the search value. If the value of the current node is equal to the search value, the function can return the node. If the value is less than the search value, the function can recursively search the left subtree. If the value is greater than the search value, the function can recursively search the right subtree. If the value is not found in the BST, the function can return null.
Here is an example of a recursive search function in Java:
class BinarySearchTree {
public static TreeNode search(TreeNode node, int value) {
if (node == null || node.value == value) {
return node;
}
if (value < node.value) {
return search(node.left, value);
}
return search(node.right, value);
}
}
In an iterative approach, you can use a loop to traverse the BST in a similar manner, using a pointer to keep track of the current node and updating it based on the comparison with the search value.
Here is an example of an iterative search function in Java:
class BinarySearchTree {
public static TreeNode search(TreeNode root, int value) {
TreeNode current = root;
while (current != null) {
if (current.value == value) {
return current;
}
if (value < current.value) {
current = current.left;
} else {
current = current.right;
}
}
return null;
}
}
To use these search functions, you will need to have a tree node class defined, such as the one shown below:
class TreeNode {
int value;
TreeNode left;
TreeNode right;
public TreeNode(int value) {
this.value = value;
this.left = null;
this.right = null;
}
}
You can then call the search function on the root node of the BST, passing in the value that you want to search for. For example:
TreeNode root = new TreeNode(5);
root.left = new TreeNode(3);
root.right = new TreeNode(7);
TreeNode node = BinarySearchTree.search(root, 3);
if (node != null) {
System.out.println("Node found: " + node.value);
} else {
System.out.println("Node not found");
}
I hope this helps! Let me know if you have any other questions.
0 Comments
if you are not getting it then ask i am glad to help