Leetcode: Symmetric Tree (Kotlin)
Kotlin

Leetcode: Symmetric Tree (Kotlin)

2024-03-20
10 min read

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:

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:

  1. Create a queue and add the root twice to the queue.

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

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

  4. 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

  5. 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.

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

Solution

{% gist https://gist.github.com/cmcoffeedev/a4b00b244a037575e3a2ea6463b5be53.js %} Thank you for taking time out of your day to read this article!