From 2530232514b2687c5933acd90db9e700466fd315 Mon Sep 17 00:00:00 2001 From: Nishant Dwivedi <135944619+nishant4500@users.noreply.github.com> Date: Fri, 25 Oct 2024 22:50:26 +0530 Subject: [PATCH] Update search-BST.md --- docs/binary-search-tree/search-BST.md | 59 ++++++++++++++++++++++++++- 1 file changed, 58 insertions(+), 1 deletion(-) diff --git a/docs/binary-search-tree/search-BST.md b/docs/binary-search-tree/search-BST.md index 788c2b2a8..23c177431 100644 --- a/docs/binary-search-tree/search-BST.md +++ b/docs/binary-search-tree/search-BST.md @@ -72,4 +72,61 @@ int main() { return 0; } -``` \ No newline at end of file +``` +### JAVA Code Implementation + +```java +// Definition for a binary search tree node +class TreeNode { + int val; + TreeNode left; + TreeNode right; + + // Constructor for initializing a TreeNode with a value + TreeNode(int x) { + val = x; + left = null; + right = null; + } +} + +public class BinarySearchTree { + + // Function to search a value in a binary search tree + public TreeNode searchBST(TreeNode root, int val) { + if (root == null || root.val == val) { + return root; + } + if (val < root.val) { + return searchBST(root.left, val); + } else { + return searchBST(root.right, val); + } + } + + public static void main(String[] args) { + BinarySearchTree bst = new BinarySearchTree(); + + // Building the binary search tree + TreeNode root = new TreeNode(4); + root.left = new TreeNode(2); + root.right = new TreeNode(7); + root.left.left = new TreeNode(1); + root.left.right = new TreeNode(3); + + // Define the target value to search for + int target = 2; + + // Search for the target value in the tree + TreeNode result = bst.searchBST(root, target); + + // Output the result + if (result != null) { + System.out.println("Found: " + result.val); + } else { + System.out.println("Value not found in the BST."); + } + } +} + +```