Search code examples
pythontreebinary-search-tree

Search in Binary Search Tree - why this code works?


I am looking into the LeetCode problem Search in a Binary Search Tree:

You are given the root of a binary search tree (BST) and an integer val.

Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null.

[...]

Example 2:

Input: root = [4,2,7,1,3], val = 5
Output: []

I am not sure why this code below will work in Python:

def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
    #base case
    if not root: return None
    if root.val == val: return root
    
    #recursion relation
    if val > root.val:
       return self.searchBST(root.right, val)
    else:
       return self.searchBST(root.left, val)

Specifically, in the question it says (1) if Tree is null, then we need to return [], (2) If value is not in the tree, we need to return null

Then for the line of code if not root: return None, does it cater to (1)? Aren’t we required to return []?


Solution

  • in the question it says (1) if Tree is null, then we need to return [], (2) If value is not in the tree, we need to return null

    That is not entirely true. It says that we need to return null, but in the example it represents the output as [].

    It is understandable that this leads to confusion, but it should be noted that LeetCode formats (serializes) the input and the output as lists (JSON notation), even though the actual input and output that your function deals with are not lists. The function gets a node instance as argument (or None), and the function is to return such a reference (or None).

    The LeetCode framework takes care of conversion of the text-based input into a node reference before calling your function, and does the reverse when dealing with the value that your function returns. In particular, when your function returns None, that will serialise to [] -- which represents an empty tree.