Search in a Binary Search Tree

Given the root of a binary search tree and an integer val, return true if val exists in the tree; otherwise return false. Pattern focus: BST Search. Follow the BST ordering rule to move left or right from the root without scanning unrelated nodes.

Input Format

root = binary tree root, val = target value

Output Format

true if val exists in the BST

Constraints

  • 1 <= number of nodes <= 10^5
  • -10^9 <= node values <= 10^9
  • root and val must satisfy the format described in inputFormat.

Examples

Example 1:

Input:

root = [4,2,7,1,3]
val = 2

Output:

true

Explanation:

Value 2 is present in the left subtree of the root.

Example 2:

Input:

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

Output:

false

Explanation:

Value 5 does not appear anywhere in the tree.

Loading...
Search in a Binary Search Tree