Skip to main content

Data Structures: How to Build an Iterator for a Binary Tree

Let’s say we already have a binary tree, and we want to build an Iterator to return the nodes in our tree in order.  If we were just listing the nodes, we could follow this recursive algorithm:


  1. Go to the left child (if it exists)
  2. Output the current node
  3. Go to the right child (if it exists)

Consider this tree:




We would start at the root (M); we’d immediately go to the left (F), then go to the left again (A).  There are no more values to go to the left, so we’d output the current node (A).  Then we’d go to the right - but there’s nothing to the right of A.  So we’d return.  This would return us to the previous level of recursion, where we’d output the current node (F).  We’d then go to the right (K); the next step would be to go to the left (J), then go to the left again (G).  We’d then output G as there’s no further left to go to; there’s nothing to the right, so we’d return to previous level of recursion (J).  We’d output J, and so on.  Eventually we’d output the values in order:

A, F, G, J, K, L, M, Z

However, for an Iterator, we can’t “pause” our recursion so we have to simulate it instead.  This means we’ll have to use a Stack to point to identify where we are in the tree.

We have 4 methods to implement:

  1. addToStack
    • This adds a node to the stack, and then adds its left child to the stack, then adds that node’s left child to the stack, until there are no more left children.
  2. Constructor
    • Here we instantiate a stack.
    • We call addToStack for the root - this adds all direct left descendants to the stack.
  3. next
    • We need to pop the stack - let’s call this node result.
    • We need to add result’s right child and all of result’s right child’s left descendants to the stack.
    • We return result’s value.
  4. hasNext
    • If the stack is empty, we don’t have anything left.
Consider the following tree again:


If we create a stack, and start with M and all left descendants to the stack, we end up with a stack that looks like this:

top => A => F => M

With A on the top of the stack.  If we call next() we return A.  If we call next() again, we get F as our result, but we add K, J, and G to the stack before returning F.  So our new stack looks like this:

top => G => J => K => M

We can call next() a few more times and return G and J; when we call next() again, we get K as our result, but we also add L to the stack before returning K.  So our new stack looks like this:

top => L => M

We call next() and return L, then we call next() again - we get M as our result, but we also add Z to the stack before returning M:

top => Z

We call next() one last time to return Z. 

Comments

Popular posts from this blog

Sheetz Sandwich Standoff: El Gringo vs Twisted Swiss

My wife left me alone for dinner tonight so I decided to check out the latest GetGo offerings... but to my great chagrin, they have no promotional subs. My travels led me to the local Sheetz, where I'd be able to keep eating the best gas station sandwiches around. To keep tradition alive, I picked the two most outrageous "Burgerz" on the menu: El Gringo and Twisted Swiss. The ingredient list is promising: Twisted Swiss is the burger with topped with swiss cheese, cole slaw, pickles, bacon, and whatever "Boom Boom Sauce" is on a pretzel bun.  El Gringo is the burger topped with pepper jack cheese, chili, Doritos, and BBQ sauce on a regular old bun. I unwrapped them both and stood back to admire the majesty before me. They're not pretty, but they do look a lot better out of the wrapper than many fast food burgers I've eaten. Twisted Swiss I expected this sandwich to be an awful mess.  It just seemed like a bunch

The Gobbler from Arby's

Stop.  Stop what you're doing and go to Arby's. Right. Now.  Have them make you a Gobbler .  This is not something you'll regret. Go. Eat this thing. Look at that bacon. Go. Arby's has a new sandwich.  It's called "The Gobbler" and as far as I can tell it's two things: a vehicle for their new deep fried turkey, and an attempt at a Thanksgiving themed sandwich.  It's also a third thing: magically delicious. move over Lucky, there's a new holiday mascot on the block Unwrapping: this actually looks like a sandwich.  It looks appetizing.  It looks like something I want to eat.  It doesn't look like the promo photo above, but it doesn't look like someone was flailing around and accidentally smashed up a sandwich, either. sexy Instagram caption goes here First bite: Wow.  I mean, "WOW."  Holy h*ck this is good.  The turkey has a really bold, meaty flavor.  It tastes a lot like turkey sliced fresh from your

Get Go Sandwich Standoff: "The General" vs "The Rogie Hoagie"

Get Go has been KILLING it lately with crazy sandwiches that are great for advertising on the radio but I've been wondering if they're actually great for eating. The new one I've been hearing about is "The General" which is like Chinese take-out on a sesame sub roll.  I hear ads for it every morning on my commute, and I see a giant billboard for it too.  It's basically chicken tenders with General Tso's sauce and egg rolls on a sesame bun.  I'm guessing they were inspired by Primanti's and decided to try to apply it to a different cuisine (I'm looking forward to The Russian Borscht sub which I'm sure is planned for later this summer). I ventured out to my local GetGo to try one of these out, only to be greeted by "The Rogie Hoagie" on the screen in addition to "The General."  What a great surprise (and additional gastronomic challenge)!  I decided to try them both and report back.  "The General" only comes