Given a binary tree, return the inorder traversal of its nodes' values iteratively without using recursion. For example: 1 \ 2 / 3 return |
Note: We know the elements can be printed in-order easily using recursion, as follow:
Excessive recursive function calls may cause memory to run out of stack space and extra overhead. Since the depth of a balanced binary search tree is about lg(n), you might not worry about running out of stack space, even when you have a million of elements. But what if the tree is not balanced? Then you are asking for trouble, because in the worst case the height of the tree may go up to n. If that is the case, stack space will eventually run out and your program will crash. To solve this issue, we need to develop an iterative solution. The idea is easy, we need a stack to store previous nodes, and a visited flag for each node is needed to record if the node has been visited before. When a node is traversed for the second time, its value will be printed. After its value is printed, we push its right child and continue from there.
Alternative Solution: First, the current pointer is initialized to the root. Keep traversing to its left child while pushing visited nodes onto the stack. When you reach a NULL node (ie, you've reached a leaf node), you would pop off an element from the stack and set it to current. Now is the time to print current's value. Then, current is set to its right child and repeat the process again. When the stack is empty, this means you're done printing.
We can even do better by refactoring the above code. The refactoring relies on one important observation:
Why this is true? To prove this, we assume the opposite, that is: the last traversed node has a right child. This is certainly incorrect, as in-order traversal would have to traverse its right child next before the traversal is done. Since this is incorrect, the last traversed node must not have a right child by contradiction. Below is the refactored code:
![]() A threaded tree, with the special threading links shown by dashed arrows. A threaded binary tree makes it possible to traverse the values in the binary tree via a linear traversal that is more rapid than a recursive in-order traversal. Further Thoughts: The answer is yes, it's possible. There's 2 possible ways that I know of:
|
|
|
classic iterative solution.
|
public ArrayList<integer> inorderTraversal(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if(root == null){
return new ArrayList<integer>();
|
|
Morris algorithm.
|
|
// this is 1337c0d3r's solution. |