Interview Bootcamp

0% completed

Solution: Invert Binary Tree

Problem Statement

Given the root of a binary tree, invert it.

Example:

Given the following two binary trees:

Constraints:

  • The number of nodes in both trees is in the range [0, 100].
  • -100 <= Node.val <= 100

Solution

This problem is quite similar to Same Tree. We can follow the same approach. After swapping left and right child of a node, we will recursively invert its left and right subtrees.

Code

Here is what our algorithm will look like:

.....

.....

.....

Like the course? Get enrolled and start learning!
I

ivanc11235

· 3 years ago

For all of the mult-threaded questions, if you code in C++, neither the Run or Submit buttons will be able to compile and run the code. I get the following compilation error, even when trying to run the official solution in the "Try it yourself" editor:

/usr/bin/ld: /tmp/cc2b5PvT.o: in function std::thread::thread<void (Solution::*)(TreeNodeT<int>*, int), Solution*, TreeNodeT<int>*&, int, void>(void (Solution::*&&)(TreeNodeT<int>*, int), Solution*&&, TreeNodeT<int>*&, int&&)': run.cpp:(.text._ZNSt6threadC2IM8SolutionFvP9TreeNodeTIiEiEJPS1_RS4_iEvEEOT_DpOT0_[_ZNSt6threadC5IM8SolutionFvP9TreeNodeTIiEiEJPS1_RS4_iEvEEOT_DpOT0_]+0x33): undefined reference to pthread_create' collect2: error: ld returned 1 exit status

A cursory online search for this error suggests that the proper fix is to