Skip to the code
cf.
+10 XP

#335 Find a Price in the Catalog Tree

easy

A product catalog keeps prices in a binary search tree: every node's left subtree holds smaller prices and its right subtree holds bigger ones. Prices are unique.

Write findPrice(root, price) that returns the node whose value is price, together with everything below it (return the node itself). If the price isn't in the tree, return null. The examples show the returned subtree in level order, and [] for null.

Example 1

Input: root = [40,20,70,10,30], price = 20
Output: [20,10,30]

20 < 40, so go left and find 20, with its children 10 and 30.

Example 2

Input: root = [40,20,70,10,30], price = 25
Output: []

25 would be under 30, but 30 has no left child, so it isn't there.

Constraints

  • 0 <= number of prices <= 10000
  • 1 <= price <= 10^7

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).