nvert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9
to
4 / \ 7 2 / \ / \ 9 6 3 1
Trivia:
This problem was inspired by this original tweet by Max Howell:
public class Solution { public TreeNode invertTree(TreeNode root) { if(root == null) return root; Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while(!queue.isEmpty()){ TreeNode node = queue.poll(); TreeNode left = node.left; node.left = node.right; node.right = left; if(node.right != null){ queue.offer(node.right); } if(node.left != null){ queue.offer(node.left); } } return root; } }
public class Solution { public TreeNode invertTree(TreeNode root) { if(root == null) return root; TreeNode left = root.left, right = root.right; root.left = invertTree(right); root.right = invertTree(left); return root; } }