FunctionRacerProblemsRace

Trim a Binary Search Tree

MediumTreesPython, JavaScript, TypeScript, Java, C++

You are given the root of a binary tree. Remove every node whose value is outside the range from low to high (both allowed), keeping the others in their original relative positions. A node that is too small is replaced by its trimmed right subtree; a node that is too large is replaced by its trimmed left subtree. Return the new root, which may be a different node or empty.

Trees appear in the tests in level order, with null for a missing child, like [3,9,20,null,null,15,7]. Each node is a TreeNode with .val, .left and .right; the class is already defined for you.

Example 1

root [3,0,4,null,2,null,null,1]
low 1
high 3
returns [3,2,null,1]

0 and 4 are removed; 2 moves up to the left of 3, and 1 stays under 2: [3,2,None,1].

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Trees problems