https://leetcode.com/problems/invert-binary-tree/
https://leetcode.com/articles/invert-binary-tree/
Because 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 .
X. https://leetcode.com/problems/invert-binary-tree/discuss/62707/Straightforward-DFS-recursive-iterative-BFS-solutions
X. Iterative
X. Iterative: Level Order traverse
Invert a binary tree.
Example:
Input:
4 / \ 2 7 / \ / \ 1 3 6 9
Output:
4 / \ 7 2 / \ / \ 9 6 3 1
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off.
https://leetcode.com/articles/invert-binary-tree/
Because 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 .
public TreeNode invertTree(TreeNode root) {
if (root == null)
return null;
TreeNode left = invertTree(root.left);
TreeNode right = invertTree(root.right);
root.left = right;
root.right = left;
return root;
}
X. https://leetcode.com/problems/invert-binary-tree/discuss/62707/Straightforward-DFS-recursive-iterative-BFS-solutions
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
final TreeNode left = root.left,
right = root.right;
root.left = invertTree(right);
root.right = invertTree(left);
return root;
}
public TreeNode invertTree(TreeNode root) {
if(root == null) return null;
TreeNode tmp = root.left;
root.left = invertTree(root.right);
root.right = invertTree(tmp);
return root;
}
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
final Deque<TreeNode> stack = new LinkedList<>();
stack.push(root);
while(!stack.isEmpty()) {
final TreeNode node = stack.pop();
final TreeNode left = node.left;
node.left = node.right;
node.right = left;
if(node.left != null) {
stack.push(node.left);
}
if(node.right != null) {
stack.push(node.right);
}
}
return root;
}
X. Iterative: Level Order traverse
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.
Space 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.
public TreeNode invertTree(TreeNode root) { if (root == null) return null; Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); while (!queue.isEmpty()) { TreeNode current = queue.poll(); TreeNode temp = current.left; current.left = current.right; current.right = temp; if (current.left != null) queue.add(current.left); if (current.right != null) queue.add(current.right); } return root; }