Easy
Search in a Binary Search Tree — C++
Full explanation · Time O(h) · Space O(1)
// Time: O(h)
// Space: O(1)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
while (root && val != root->val) {
if (val < root->val) {
root = root->left;
} else {
root = root->right;
}
}
return root;
}
};