Iteration

Below is our original solution, which uses a recursive function height. Try converting this code to iterative code, so that the function doesn't call itself.

First Few Test Cases:

The trick is to put the node in the stack, and along with it, keep a label whether or not we're calling it for the first time. If this is the first time we're calling it, we should compute height on the left node first and then come back. Then when we come back for the second time, we're ready to compute the height.

Notice that we add elements to the stack in reverse order because stacks are last-in-first-out.

We also store all the heights we've computed in some data structure so we can access them wherever we need them. (You can make this more general/readable, but since we're just implementing a less convenient and less general version of Python's Call Stack, it's not really worth the thought).

Time Complexity O(n)O(n)

Space Complexity O(n)O(n). The stack grows in the same exact way as the recursive solution, so it has the same space complexity.

Mark as Completed:
Submits:
height
Imports:
TreeNode
Test your code to get an output here!
height(
)
Test your code to get an output here!