Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

BST Contains

BSTeasy

A BST node is `{ val, left, right }`. Implement `bstContains(root, target)` returning whether `target` exists, using the BST ordering.

Sample tests

Input: bstContains({"val":5,"left":{"val":3,"left":null,"right":null},"right":{"val":8,"left":null,"right":null}}, 3)
Output: true
Input: bstContains({"val":5,"left":{"val":3,"left":null,"right":null},"right":{"val":8,"left":null,"right":null}}, 7)
Output: false

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Searching both subtrees ignores the BST property and is slower.

Learning resources

  • Wikipedia: Binary search tree
Approach & explanation (try first)

The BST property means you branch one way each step, giving O(h) time (h is the height).

Loading...
⌘/Ctrl + Enter

Run your code to see results.