DEV Community

Cover image for Leetcode: Symmetric Tree (Kotlin)
Christopher Coffee
Christopher Coffee

Posted on • Edited on

Leetcode: Symmetric Tree (Kotlin)

Symmetric Tree is an “Easy” tagged Leetcode problem. The problem states “Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).”

They give us two examples:

Image description

Brainstorming:

We can have a queue to check if the root’s left and right children are identical.

These are the steps we can take to arrive at our solution:
Create a queue and add the root twice to the queue.

  1. As long as there is a TreeNodes in the queue, we will take two TreeNodes.

  2. If they are both null, we have arrived at null leaf nodes, so continue.

  3. Next, if either node is null, we will return false since we already are checking if both are null beforehand. This is similar to the given Example 2.

  4. Lastly, we also need to check if the values are the same. Of course, if the values are not the same, they are not symmetric.

  5. We will add each of the two current nodes opposite nodes to the queue.

Code:

class Solution {
fun isSymmetric(root: TreeNode?): Boolean {
val queue = LinkedList<TreeNode?>()
queue.offer(root)
queue.offer(root)
while( queue.isNotEmpty() ){
val one = queue.poll()
val two = queue.poll()
if(one == null && two == null) continue
if(one == null || two == null) return false
if(one?.`val` != two?.`val`) return false
queue.offer(one.left)
queue.offer(two.right)
queue.offer(two.left)
queue.offer(one.right)
}
return true
}
}

Codelab version of this solution:
https://cmcoffeedev.com/codelabs/leetcode-symmetric-tree/index.html#0

Video Solution:

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay