Welcome to my personal website. I use this space to share some of my thoughts and software that I write in my free time. Sometimes I also publish photos. If you want to get in touch please use LinkedIn or Mastodon.
The task is to determine if a tree is symmetric, meaning mirrored along the root node. The usual tree structure is given in form of a TreeNode.
The logic itself is quite straightforward look at two nodes and compare the values. If their respective values are the same look at both of their children and compare them. Repeat this process until every node is visited.
There are some special cases here that need to be handled. The left child can be None while the right child is not and vice versa. If both children are None, return True and do not proceed because this means we reached a leaf node.
The recursive solution looks like this.
And the iterative solution looks like this.
Test both solutions with the following code:
About the author
Friedrich Ewald is an experienced Software Engineer with a Master's degree in Computer Science. He started this website in late 2015, mostly as a digital business card. He is interested in Go, Python, Ruby, SQL- and NoSQL-databases, machine learning and AI and is experienced in building scalable, distributed systems and micro-services at multiple larger and smaller companies.