Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.thealgorithms.datastructures.trees;

/**
* Inverts a binary tree by swapping the left and right children of every node.
*
* <p>Example:
* <pre>
* 4 4
* / \ / \
* 2 7 -> 7 2
* / \ / \ / \ / \
* 1 3 6 9 9 6 3 1
* </pre>
*
* <p>Time complexity: O(n), Space complexity: O(h) where h is tree height.
*
* @see <a href="https://leetcode.com/problems/invert-binary-tree/">LeetCode #226</a>
*/
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;
}
}
Original file line number Diff line number Diff line change
@@ -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);
}
}
Loading