All prompts are owned by LeetCode. To view the prompt, click the title link above.
First completed : July 17, 2024
Last updated : July 17, 2024
Related Topics : Tree, Binary Search Tree, Binary Tree
Acceptance Rate : 81.35 %
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* searchBST(struct TreeNode* root, int val) {
if (!root)
return NULL;
if (root->val == val)
return root;
if (root->val < val)
return searchBST(root->right, val);
return searchBST(root->left, val);
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
if (root == null || root.val == val) {
return root;
}
if (root.val < val) {
return searchBST(root.right, val);
}
return searchBST(root.left, val);
}
}
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root :
return None
if root.val == val :
return root
if val < root.val :
return self.searchBST(root.left, val)
return self.searchBST(root.right, val)