700. 二叉搜索树中的搜索
一、递归
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if(!root)return NULL;
if(root->val==val)return root;
if(root->val>val)
return searchBST(root->left,val);
if(root->val<val)
return searchBST(root->right,val);
return NULL;
}
};
二、迭代法
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
while (root != NULL) {
if (root->val > val) root = root->left;
else if (root->val < val) root = root->right;
else return root;
}
return NULL;
}
};