Search in a Binary Search Tree LeetCode Challenge June Day 15

Quoestion: ClickHere

Example:
Given Tree


You Should Return This:


Recursive Approach:
1.Check if root's value is equal to search value or not if yes return root
2.if search value is > root's value update root as root.right
3.if search value is < root's value update root as root.left
4.Repeat above steps until leaf node
5.If search value is not found then return None

Python Code:
class Solution:
    
    def searchBST(self, root: TreeNode, value: int) -> TreeNode:
        print(root.val)
        if root.val == value:
            return root
        if root.val < value:
            if root.right:
                return self.searchBST(root.right,value)
        if root.val > value:
            if root.left:
                return self.searchBST(root.left,value)

        return None

Post a Comment

0 Comments