LeetCode 100 Same Tree

Victoria
2 min readJun 8, 2021

The code I wrote:

The Answer:

I want to take a moment and reflect why I have such a messy code and how to improve. I realized that for some mysterious reasons I have been keep making the same mistakes when I try to solve the issue for a tree. I think the most obvious problem I usually make is that:

  1. I wanted to check the node itself and at the same time I also want to check the left and right. This is clearly duplicated work because I could just wait for the next recursive call to check it.
  2. I wanted to check the status of if the node is null or node by manually writing a if statement and else if to check if one of them is null. This is, again, duplicated work. I can totally just check if both of them are nulls. And if not, then if any of them are null this means it is wrong. I can totally use a || statement to do that.

If statement a means: node1 == null

statement b means: node2 == null

We want to determine if a == b is true then we should go like:

a && b -> we can return TRUE if they are both null.

a || b means a && !b or !a && b, either way, a==b will be false and we can return FALSE.

!a && !b -> We will not know if a == b because in this case they are both not null and therefore we can start further instructions to find out if their values are the same.

Conclusion: I think I made the mistake because I neglected that checking value is the last step and we HAVE TO check the status of null before the last step.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Victoria
Victoria

Written by Victoria

"What if I fall?" "Oh my darling, but what if you fly?"

No responses yet

Write a response