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.
1#include <stdio.h>
2#include <stdlib.h>
3
4struct TreeNode {
5 int val;
6 struct TreeNode *left;
7 struct TreeNode *right;
8};
9
10struct TreeNode* searchBST(struct TreeNode* root, int val) {
11 if (root == NULL || root->val == val) {
12 return root;
13 }
14 if (val < root->val) {
15 return searchBST(root->left, val);
16 }
17 return searchBST(root->right, val);
18}
This C code defines a recursive function searchBST
that starts from the root
of the tree. It checks if the current node is NULL
or matches the target val
. If it matches, it returns the node. If the target is smaller, it recurses into the left subtree; otherwise, it goes to the right 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.
1
The Python iteration involves a simple while
loop to traverse the tree, going left or right at each node according to the BST properties, efficiently locating the target node.