FunctionRacerProblemsRace

Same Up to Swapping Children

HardTreesPython, JavaScript, TypeScript, Java, C++

You are given the roots first and second of two binary trees. Values may repeat.

One move picks a node and swaps its left and right child, together with everything below them. A node with one child can be picked too: the child changes sides.

Return True if some number of moves turns first into second, and False otherwise.

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

first [1,2,3,4]
second [1,3,2,null,null,null,4]
returns true

Swap the children of the root, then the children of the node 2.

Example 2

first [1,2,3,4]
second [1,3,2,4]
returns false

In the first tree the node 4 hangs under 2. In the second it hangs under 3.

Example 3

first [1,2]
second [1,null,2]
returns true

Swapping the children of the root moves the only child to the other side.

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