题目来源:https://leetcode.cn/problems/search-in-a-binary-search-tree/description/
C++题解1:二叉搜索树,右节点大于当前节点,左右节点小于当前节点,因此可以根据当前节点值与目标值的大小比较进行搜索。
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
TreeNode* cur = root;
while(cur){
if(val > cur->val) cur = cur->right;
else if(val < cur->val) cur = cur->left;
else return cur;
}
return cur;
}
};
C++题解2:递归法。不用遍历整棵树,所以要有返回值。
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if (root == NULL || root->val == val) return root;
TreeNode* result = NULL;
if (root->val > val) result = searchBST(root->left, val);
if (root->val < val) result = searchBST(root->right, val);
return result;
}
};