Skip to content
Merged
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,53 @@
package com.thealgorithms.datastructures.trees;

import com.thealgorithms.datastructures.trees.BinaryTree.Node;

/**
* Check if a binary tree is symmetric or not.
* A binary tree is a symmetric tree if the left and right subtree of root are mirror image.
* Below is a symmetric tree
* 1
* / \
* 2 2
* / \ / \
* 3 4 4 3
*
* Below is not symmetric because values is different in last level
* 1
* / \
* 2 2
* / \ / \
* 3 5 4 3
* <p>
* Approach:
* Recursively check for left and right subtree of root
* 1. left subtrees root's values should be equal right subtree's root value
* 2. recursively check with left subtrees' left child VS right subtree's right child AND
* left subtree's right child VS right subtree left child
* Complexity
* 1. Time: O(n)
* 2. Space: O(lg(n)) for height of tree
*
* @author kumanoit on 10/10/22 IST 12:52 AM
*/
public class CheckTreeIsSymmetric {

public static boolean isSymmetric(Node root) {
if (root == null) {
return true;
}
return isSymmetric(root.left, root.right);
}

private static boolean isSymmetric(Node leftSubtreeRoot, Node rightSubtreRoot) {
if (leftSubtreeRoot == null && rightSubtreRoot == null) {
return true;
}

if (leftSubtreeRoot == null || rightSubtreRoot == null || leftSubtreeRoot.data != rightSubtreRoot.data) {
return false;
}

return isSymmetric(leftSubtreeRoot.right, rightSubtreRoot.left) && isSymmetric(leftSubtreeRoot.left, rightSubtreRoot.right);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.thealgorithms.datastructures.trees;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
* @author kumanoit on 10/10/22 IST 1:02 AM
*/
public class CheckTreeIsSymmetricTest {

@Test
public void testRootNull() {
assertTrue(CheckTreeIsSymmetric.isSymmetric(null));
}

@Test
public void testSingleNodeTree() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{100});
assertTrue(CheckTreeIsSymmetric.isSymmetric(root));
}

@Test
public void testSymmetricTree() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1,2,2,3,4,4,3});
assertTrue(CheckTreeIsSymmetric.isSymmetric(root));
}

@Test
public void testNonSymmetricTree() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1,2,2,3,5,4,3});
assertFalse(CheckTreeIsSymmetric.isSymmetric(root));
}

}