文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
- Iterative
/**
* 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) {
TreeNode* current = root;
while(current) {
if(current->val == val) {
return current;
}
else if(current->val < val) {
current = current->right;
}
else {
current = current->left;
}
}
return NULL;
}
};
- Recursive
/**
* 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) {
if(!root) {
return NULL;
}
else if(root->val == val) {
return root;
}
else if(root->val < val) {
return searchBST(root->right, val);
}
else {
return searchBST(root->left, val);
}
}
};