ZhongKuo0228 / study

0 stars 0 forks source link

700. Search in a Binary Search Tree #98

Open fockspaces opened 10 months ago

fockspaces commented 10 months ago

use the recursion to traverse the tree

  1. set root is None as base case
  2. if val is greater than current root value, go right subtree
  3. otherwise, go left
# 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 root.val < val:
            return self.searchBST(root.right, val)
        return self.searchBST(root.left, val)