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