Add check if tree is symmetric or not (fixes #3471) (#3472)

Co-authored-by: Amit Kumar <akumar@indeed.com>
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
This commit is contained in:
Amit Kumar 2022-10-30 13:59:22 +05:30 committed by GitHub
parent 23eec39a29
commit 3542f1c4c1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 89 additions and 0 deletions

View File

@ -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);
}
}

View File

@ -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));
}
}