-
Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathCheckTreeIsSymmetric.java
59 lines (52 loc) · 2.14 KB
/
CheckTreeIsSymmetric.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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 final class CheckTreeIsSymmetric {
private 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 rightSubtreeRoot) {
if (leftSubtreeRoot == null && rightSubtreeRoot == null) {
return true;
}
if (isInvalidSubtree(leftSubtreeRoot, rightSubtreeRoot)) {
return false;
}
return isSymmetric(leftSubtreeRoot.right, rightSubtreeRoot.left) && isSymmetric(leftSubtreeRoot.left, rightSubtreeRoot.right);
}
private static boolean isInvalidSubtree(Node leftSubtreeRoot, Node rightSubtreeRoot) {
return leftSubtreeRoot == null || rightSubtreeRoot == null || leftSubtreeRoot.data != rightSubtreeRoot.data;
}
}