4 / \ 2 7 / \ / \ 1 3 6 9to
4 / \ 7 2 / \ / \ 9 6 3 1Trivia:
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.
This is a classic tree problem that is best-suited for a recursive approach.
\nAlgorithm
\nThe 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 .
\nJava
\npublic 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
\nSince 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 .
\nAlternatively, we can solve the problem iteratively, in a manner similar to breadth-first search.
\nAlgorithm
\nThe 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.
\nJava
\npublic 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
\nSince 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