Sponsored
Sponsored
This approach uses the recursive traversal of the BST properties. It checks if the current node's value is equal to the target value. If it is, it returns the subtree rooted at the current node. If the target value is less than the current node, it recurses into the left subtree; if greater, it recurses into the right subtree. This method leverages the BST's inherent properties to narrow down the search.
Time Complexity: O(h) where h is the height of the tree, as we traverse from the root to a leaf.
Space Complexity: O(h) due to the recursion stack.
1function TreeNode(val, left = null, right = null) {
2 this.val = val;
3 this.left = left;
4 this.right = right;
5}
6
7var searchBST = function(root, val) {
8 if (!root || root.val === val) {
9 return root;
10 }
11 if (val < root.val) {
12 return searchBST(root.left, val);
13 }
14 return searchBST(root.right, val);
15};
The JavaScript function searchBST
efficiently locates the node within the binary search tree using recursion. It returns the subtree if found; otherwise, continues to search the appropriate subtree.
In this approach, we use an iterative solution instead of recursion to save stack space. Starting from the root, we use a loop to traverse the tree. At each node, we check if it matches the target value. If it matches, we return the node; if not, we decide to move to the left or right child based on the BST property. The absence of a matching node returns null
.
Time Complexity: O(h) where h is tree height.
Space Complexity: O(1) since we're only using a few extra pointers.
This code converts the recursive search logic into an iterative one by using a while
loop. It repeatedly narrows down the search area based on the value comparison until it finds the value or reaches a NULL
node.