700. 二叉搜索树中的搜索

一、递归

  1. class Solution {
  2. public:
  3. TreeNode* searchBST(TreeNode* root, int val) {
  4. if(!root)return NULL;
  5. if(root->val==val)return root;
  6. if(root->val>val)
  7. return searchBST(root->left,val);
  8. if(root->val<val)
  9. return searchBST(root->right,val);
  10. return NULL;
  11. }
  12. };

二、迭代法

  1. class Solution {
  2. public:
  3. TreeNode* searchBST(TreeNode* root, int val) {
  4. while (root != NULL) {
  5. if (root->val > val) root = root->left;
  6. else if (root->val < val) root = root->right;
  7. else return root;
  8. }
  9. return NULL;
  10. }
  11. };