This website contains ALL LeetCode **Premium** problems for
**FREE!!**.

All leaked interview problems are collected from Internet.

All leaked interview problems are collected from Internet.

Invert a binary tree.

4 / \ 2 7 / \ / \ 1 3 6 9to

4 / \ 7 2 / \ / \ 9 6 3 1

This problem was inspired by this original tweet by Max Howell:

Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.

b'

\n\n## Solution

\n

\n#### Approach #1 (Recursive) [Accepted]

\n\n

\n#### Approach #2 (Iterative) [Accepted]

\n\n

'
\n

This is a classic tree problem that is best-suited for a recursive approach.

\n**Algorithm**

The inverse of an empty tree is the empty tree. The inverse of a tree with root , and subtrees and , is a tree with root , whose right subtree is the inverse of , and whose left subtree is the inverse of .

\n**Java**

public TreeNode invertTree(TreeNode root) {\n if (root == null) {\n return null;\n }\n TreeNode right = invertTree(root.right);\n TreeNode left = invertTree(root.left);\n root.left = right;\n root.right = left;\n return root;\n}\n

**Complexity Analysis**

Since each node in the tree is visited only once, the time complexity is , where is the number of nodes in the tree. We cannot do better than that, since at the very least we have to visit each node to invert it.

\nBecause of recursion, function calls will be placed on the stack in the worst case, where is the height of the tree. Because , the space complexity is .

\n\n

Alternatively, we can solve the problem iteratively, in a manner similar to breadth-first search.

\n**Algorithm**

The idea is that we need to swap the left and right child of all nodes in the tree. So we create a queue to store nodes whose left and right child have not been swapped yet. Initially, only the root is in the queue. As long as the queue is not empty, remove the next node from the queue, swap its children, and add the children to the queue. Null nodes are not added to the queue. Eventually, the queue will be empty and all the children swapped, and we return the original root.

\n**Java**

public TreeNode invertTree(TreeNode root) {\n if (root == null) return null;\n Queue<TreeNode> queue = new LinkedList<TreeNode>();\n queue.add(root);\n while (!queue.isEmpty()) {\n TreeNode current = queue.poll();\n TreeNode temp = current.left;\n current.left = current.right;\n current.right = temp;\n if (current.left != null) queue.add(current.left);\n if (current.right != null) queue.add(current.right);\n }\n return root;\n}\n

**Complexity Analysis**

Since each node in the tree is visited / added to the queue only once, the time complexity is , where is the number of nodes in the tree.

\nSpace complexity is , since in the worst case, the queue will contain all nodes in one level of the binary tree. For a full binary tree, the leaf level has leaves.

\nAnalysis written by: @noran

\n