Leetcode 700. Search in a Binary Search Tree
Given the root node of a binary search tree (BST) and an integer value, write a function to search for a node in the BST that matches the given value. Return the node that contains the value, or nullptr
if such a node does not exist.
Input: root = [4,2,7,1,3], val = 2
Output: Node with value 2
Input: root = [4,2,7,1,3], val = 5
Output: nullptr
1 <= Node.val <= 10^7
root
is a binary search tree.For the sake of this implementation, I will use a recursive approach. The function signature will be:
TreeNode* searchBST(TreeNode* root, int val);
/**
* Definition for a binary tree node.
*/
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if (root == nullptr || root->val == val) {
return root;
} else if (val < root->val) {
return searchBST(root->left, val);
} else {
return searchBST(root->right, val);
}
}
};
nullptr
, return nullptr
indicating the node with the given value was not found.searchBST
on the left subtree.searchBST
on the right subtree.By dividing the problem this way, we efficiently reduce the search space by half on every recursive call, taking advantage of the properties of a binary search tree.
This recursive approach is simple and leverages the properties of a binary search tree effectively.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?