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.
Given a binary tree, write an iterator that performs in-order iteration and returns next as well as hasNext. It is guaranteed that next is never called on an empty tree.
The naive approach looks as follows. Note that the space complexity here is O(n).
To further improve this, we can store the current nodes in a stack so that we only need to pop from the stack with time complexity O(1). The approach here is that we only iterate over the tree until we find the first leaf node, which happens on average after the height h of the tree. When popping the first element, we look for the next leaf node which can be found by going to the right and subsequently to the left. Repeat this process until the list is empty.
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.