Skip to content
BASA DSA

Invert Binary Tree

EasyTrees

Swap the left and right children at every node of a binary tree and return its root. Trees use breadth-first value arrays with null for missing children.

Example 1

Argument 1 tree: level-order input; omitted children are null.Argument 1 tree: level-order input; omitted children are null. Vertices: node 0: 4, node 1: 2, node 2: 7, node 3: 1, node 4: 3. Edges: node 0 (4) — node 1 (2) left child; node 0 (4) — node 2 (7) right child; node 1 (2) — node 3 (1) left child; node 1 (2) — node 4 (3) right child.42713
Argument 1 tree: level-order input; omitted children are null.

Input
root = [4,2,7,1,3]
Output
[4,7,2,null,null,3,1]

Explanation

Swap 2 and 7, then 1 and 3 under node 2; null holes preserve the new shape.

Example 2

Argument 1 tree: empty tree (null root).
Input
root = []
Output
null

Explanation

Inverting an empty tree returns an empty tree.

Example 3

Argument 1 tree: level-order input; omitted children are null.Argument 1 tree: level-order input; omitted children are null. Vertices: node 0: 8. Edges: none.8
Argument 1 tree: level-order input; omitted children are null.

Input
root = [8]
Output
[8]

Explanation

A leaf has no children to swap.

Constraints

  • 0 <= number of nodes <= 10000
  • Node values are signed 32-bit integers

Function contractinvertTreeArguments: tree
Loading draft…
SolutionRuns on your device
Loading draft…