Skip to content

Latest commit

 

History

History
103 lines (86 loc) · 2.38 KB

_700. Search in a Binary Search Tree.md

File metadata and controls

103 lines (86 loc) · 2.38 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : July 17, 2024

Last updated : July 17, 2024


Related Topics : Tree, Binary Search Tree, Binary Tree

Acceptance Rate : 81.35 %


Solutions

C

/**
 * 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);

}

Java

/**
 * 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);
    }
}

Python

# 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)