File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ import DS .TreeNode ;
2
+
3
+ /*
4
+ // Definition of TreeNode:
5
+ class TreeNode {
6
+ public int val;
7
+ public TreeNode left;
8
+ public TreeNode right;
9
+ public TreeNode(int val) {
10
+ this.val = val;
11
+ }
12
+ }
13
+ */
14
+
15
+ public class BinaryTreeSymmetry {
16
+ public boolean binaryTreeSymmetry (TreeNode root ) {
17
+ if (root == null ) {
18
+ return true ;
19
+ }
20
+ return compareTrees (root .left , root .right );
21
+ }
22
+
23
+ private boolean compareTrees (TreeNode node1 , TreeNode node2 ) {
24
+ // Base case: if both nodes are null, they're symmetric.
25
+ if (node1 == null && node2 == null ) {
26
+ return true ;
27
+ }
28
+ // If one node is null and the other isn't, they aren't symmetric.
29
+ if (node1 == null || node2 == null ) {
30
+ return false ;
31
+ }
32
+ // If the values of the current nodes don't match, trees aren't symmetric.
33
+ if (node1 .val != node2 .val ) {
34
+ return false ;
35
+ }
36
+ // Compare the 'node1's left subtree with 'node2's right subtree. If these
37
+ // aren't symmetric, the whole tree is not symmetric.
38
+ if (!compareTrees (node1 .left , node2 .right )) {
39
+ return false ;
40
+ }
41
+ // Compare the 'node1's right subtree with 'node2's left subtree.
42
+ return compareTrees (node1 .right , node2 .left );
43
+ }
44
+ }
You can’t perform that action at this time.
0 commit comments