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.
1class TreeNode {
2public:
3 int val;
4 TreeNode *left;
5 TreeNode *right;
6 TreeNode() : val(0), left(nullptr), right(nullptr) {}
7 TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
8 TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
9};
10
11class Solution {
12public:
13 TreeNode* searchBST(TreeNode* root, int val) {
14 if (!root || root->val == val) {
15 return root;
16 }
17 if (val < root->val) {
18 return searchBST(root->left, val);
19 }
20 return searchBST(root->right, val);
21 }
22};
This C++ implementation uses a class method searchBST
for the recursive traversal. It returns the node with the target value or nullptr
if the value isn’t found in the tree.
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.
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.