给定二叉搜索树(BST)的根节点 root 和一个整数值 val。
你需要在 BST 中找到节点值等于 val 的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 null 。
来源:力扣(LeetCode)
题目链接:https://leetcode-cn.com/problems/search-in-a-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题方法一:迭代
/**
* 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(root->val == val) return root;
root = root->val > val ? root->left : root->right;
}
return nullptr;
}
};
解题方法二:递归
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if(root && root->val == val) return root;
if(root && root->val > val) return searchBST(root->left, val);
if(root && root->val < val) return searchBST(root->right, val);
return nullptr;
}
};