InvertBinaryTreeSolution { static TreeNode invertTreeBFS(TreeNode root) { if (root == null) return null; final Queue<TreeNode> stack = new LinkedList<>(); stack.offer(root); while (!stack.isEmpty()) { final TreeNode node = stack.poll(); final TreeNode left = node.left; node.left = node.right; node.right = left; if (node.left != null) { stack.offer(node.left); } if (node.right != null) { stack.offer(node.right); } } return root; }    }
@Test public void invertTreeBFS() { TreeNode root0 = new TreeNode(0); TreeNode left1 = new TreeNode(1); TreeNode right1 = new TreeNode(2); TreeNode left21 = new TreeNode(21); TreeNode right22 = new TreeNode(22); TreeNode left23 = new TreeNode(23); TreeNode right24 = new TreeNode(24); root0.left = left1; root0.right = right1; left1.left = left21; left1.right = right22; right1.left = left23; right1.right = right24; assertEquals(21, root0.left.left.val); assertEquals(24, InvertBinaryTreeSolution.invertTreeBFS(root0).left.left.val); }