MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / compareTrees

Function compareTrees

kotlin/Trees/BinaryTreeSymmetry.kt:20–40  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

18}
19
20fun 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}

Callers 1

binaryTreeSymmetryFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected