LeetCode 100 Same Tree
The code I wrote:
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:
- 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.
- 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.