diff --git a/src/main/java/com/thealgorithms/datastructures/trees/InvertBinaryTree.java b/src/main/java/com/thealgorithms/datastructures/trees/InvertBinaryTree.java new file mode 100644 index 000000000000..927c8e775b37 --- /dev/null +++ b/src/main/java/com/thealgorithms/datastructures/trees/InvertBinaryTree.java @@ -0,0 +1,32 @@ +package com.thealgorithms.datastructures.trees; + +/** + * Inverts a binary tree by swapping the left and right children of every node. + * + *

Example: + *

+ *      4                4
+ *     / \              / \
+ *    2   7    ->      7   2
+ *   / \ / \          / \ / \
+ *  1  3 6  9        9  6 3  1
+ * 
+ * + *

Time complexity: O(n), Space complexity: O(h) where h is tree height. + * + * @see LeetCode #226 + */ +public final class InvertBinaryTree { + private InvertBinaryTree() { + } + + public static BinaryTree.Node invertTree(BinaryTree.Node root) { + if (root == null) { + return null; + } + BinaryTree.Node temp = root.left; + root.left = invertTree(root.right); + root.right = invertTree(temp); + return root; + } +} diff --git a/src/test/java/com/thealgorithms/datastructures/trees/InvertBinaryTreeTest.java b/src/test/java/com/thealgorithms/datastructures/trees/InvertBinaryTreeTest.java new file mode 100644 index 000000000000..875a234869eb --- /dev/null +++ b/src/test/java/com/thealgorithms/datastructures/trees/InvertBinaryTreeTest.java @@ -0,0 +1,43 @@ +package com.thealgorithms.datastructures.trees; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import org.junit.jupiter.api.Test; + +public class InvertBinaryTreeTest { + + @Test + public void testNullRoot() { + assertNull(InvertBinaryTree.invertTree(null)); + } + + @Test + public void testSingleNode() { + BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1}); + InvertBinaryTree.invertTree(root); + assertEquals(1, root.data); + assertNull(root.left); + assertNull(root.right); + } + + /* + 4 4 + / \ / \ + 2 7 -> 7 2 + / \ / \ / \ / \ + 1 3 6 9 9 6 3 1 + */ + @Test + public void testInvertTree() { + BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {4, 2, 7, 1, 3, 6, 9}); + InvertBinaryTree.invertTree(root); + assertEquals(4, root.data); + assertEquals(7, root.left.data); + assertEquals(2, root.right.data); + assertEquals(9, root.left.left.data); + assertEquals(6, root.left.right.data); + assertEquals(3, root.right.left.data); + assertEquals(1, root.right.right.data); + } +}