题目链接: 二叉搜索树中的搜索
有关题目
给定二叉搜索树(BST)的根节点和一个值。
你需要在BST中找到节点值等于给定值的节点。
返回以该节点为根的子树。 如果节点不存在,则返回 NULL。


在上述示例中,如果要找的值是 5,但因为没有节点值为 5,我们应该返回 NULL。
题解
法一:递归
参考官方题解

代码一:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if (root == nullptr)
return nullptr;
if (root->val == val)
return root;
return (root->val > val ? searchBST(root->left, val) : searchBST(root->right, val));
}
};
代码二:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if (root == nullptr)
return nullptr;
if (val == root->val)
return root;
return searchBST(root->val > val ? root->left : root->right, val);
}
};

法二:迭代
参考官方题解
代码一:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
while(root)
{
if (val > root->val)
root = root->right;
else if (val < root->val)
root = root->left;
else
return root;
}
return nullptr;
}
};
代码二:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
while(root)
{
if (val == root->val)
return root;
root = root->val > val ? root->left : root->right;
}
return nullptr;
}
};

274

被折叠的 条评论
为什么被折叠?



