FunctionRacerProblemsRace

Two Swapped Values

HardTreesPython, JavaScript, TypeScript, Java, C++

You are given the root of a binary tree that used to be a binary search tree: everything left of a node was smaller than it, and everything right of it was larger. Then the values of exactly two nodes were swapped by mistake.

Put the two values back and return the root. The shape of the tree must stay as it is.

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 [5,8,3,1,4,6,9]
returns [5,3,8,1,4,6,9]

The values 8 and 3 stand in each other's place. In sorted order the tree reads 1, 8, 4, 5, 6, 3, 9, with two drops.

Example 2

root [2,3,1]
returns [2,1,3]

The values 3 and 1 are swapped. They are neighbors in sorted order, so there is only one drop.

Example 3

root [1,2]
returns [2,1]

A parent and its child are swapped.

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