In recursive DFS traversal, we have three basic elements to traverse: root node, left subtree, and right subtree. Each traversal process nodes in a different order, where recursive code is simple and easy to visualize i.e. one function parameter and 3-4 lines of code. The critical question is: How can we convert recursive tree traversal into an iterative tree traversal? Let’s think.
In recursive code, compiler uses call stack in the background to convert it into iterative code. This call stack stores information like local variables, input parameters, the state of function calls, etc. So, for iterative implementation, we need to mimic what compiler does when we run recursive code! In other words: We need to use an explicit stack to simulate the execution of recursion.
Sometimes, iterative implementation using a stack becomes complex due to many input variables, complex additional operations, and complex nature of recursive calls. In situations like binary tree traversal, recursion is simple, and we can easily convert it into iterative code.
Preorder and inorder traversals are tail-recursive, i.e., there are no extra operations after the final recursive call. So the implementation of preorder and inorder using a stack is easy to understand. On the other side, postorder traversal is non-tail recursive because there is one extra operation after the last recursive call (we process the root node). So implementing postorder using a stack can be a little tricky. But if we follow the order of nodes in recursive postorder, we can easily implement it iteratively!
To simulate the recursive tree traversal into an iterative traversal, we need to understand the flow of recursive calls. If we observe, we visit each node three times:
Let's revise the preorder traversal: We first process the root node, then traverse the left subtree, and finally, traverse the right subtree. So tracking the correct flow of recursion will give us a better picture.
We first process the root. Then go to the left subtree and process the root node of the left subtree. Then we continue going left in the same way until we reach the leftmost node.
The idea of iterative preorder traversal: When we visit any node for the first time, we process it, push that node into the stack (to process the right subtree of that node later), and go to the left child. If there is no left child, we remove the top node from the stack and go to the right child of that node. Now we continue the same process for the subtree rooted at the right child.
We use a stack treeStack and pointer currNode to track the current node. At the start, we initialize currNode with the root node. Now we run a loop until treeStack is not empty or currNode != NULL. Inside the loop:
void iterativePreorder(TreeNode root)
{
if(root == NULL)
return
stack<TreeNode> treeStack
TreeNode currNode = root
TreeNode prevNode = NULL
while(treeStack.empty() == false || currNode != NULL)
{
if(currNode != NULL)
{
process(currNode->data)
treeStack.push(currNode)
currNode = currNode->left
}
else
{
prevNode = treeStack.top()
treeStack.pop()
currNode = prevNode->right
}
}
}
In the above code, we are storing any node in the stack to access the right subtree of that node later in preorder. So instead of storing that node, we can directly store the right child of that node. This will help us to optimize the above solution by reducing the stack space. How? Think and explore!
void iterativePreorderOptimized(TreeNode root)
{
if(root == NULL)
return
stack<TreeNode> treeStack
TreeNode currNode = root
while(treeStack.empty() == false || currNode != NULL)
{
if(currNode != NULL)
{
process(currNode->data)
if(currNode->right != NULL)
treeStack.push(currNode->right)
currNode = currNode->left
}
else
{
currNode = treeStack.top()
treeStack.pop()
}
}
}
If we observe the processing of each node during preorder traversal, it looks like this: We first process the node, then the left child, and finally the right child. To maintain this order using a stack, we process the node first, then push the right child, followed by the left child. This way, when we pop nodes from the stack, the left child will appear before the right child.
void iterativePreorder(TreeNode root)
{
if(root == NULL)
return
stack<TreeNode> treeStack
TreeNode currNode
treeStack.push(root)
while(treeStack.empty() == false)
{
currNode = treeStack.top()
treeStack.pop()
process (currNode->data)
if(currNode->right != NULL)
treeStack.push(currNode->right)
if(currNode->left != NULL)
treeStack.push(currNode->left)
}
}
Each node is pushed into and popped out of the stack only once, so we are doing a constant number of operations for each node. Time complexity = n* O(1) = O(n). We are using one stack, and the size of the stack depends on the height of the binary tree. So, space complexity is O(h).
In an inorder traversal, we first process the left subtree, then the root node, and finally the right subtree. How can we simulate this process using a stack? Let’s understand this by exploring the flow of recursion.
We start from the root node, then move to the root of the left subtree, and so on, until we reach the leftmost node. In this way, recursion will first process the leftmost node.
The idea for iterative in-order using a stack: Before processing the left subtree of any node, we need to save that node on the stack to process the node and right subtree of that node later. So we keep moving left and inserting nodes inside the stack. Once we reach the NULL node, we pop the node from the top of the stack, process it, and go to the right child of that node to traverse the right subtree.
We create an empty stack treeStack and declare a pointer currNode to track the current node. Now, we run a loop until treeStack is empty and currNode is NULL. Inside the loop:
void iterativeInorder(TreeNode root)
{
if(root == NULL)
return
stack<TreeNode> treeStack
TreeNode currNode = root
while(treeStack.empty() == false || currNode != NULL)
{
if(currNode != NULL)
{
treeStack.push(currNode)
currNode = currNode->left
}
else
{
currNode = treeStack.top()
treeStack.pop()
process (currNode->data)
currNode = currNode->right
}
}
}
Each node is pushed into and popped out of the treeStack only once, so we are doing a constant number of operations for each node. The time complexity = n * O(1) = O(n). The space complexity is O(h) since we are using one stack, and the size of the stack depends on the height of the binary tree.
In a postorder traversal, we first process the left subtree, then the right subtree, and finally the root node. In other words, we process all the nodes in the left and right subtrees before processing the root node. How can we simulate this process using a stack? Let's follow the flow of recursion.
We start from the root, then move to the root of left subtree, and so on, until we reach the leftmost node.
The idea of iterative post-order traversal: Before processing the left subtree of any node, we need to save two things on the stack: (1) The right child of the current node to process the right subtree after the traversal of the left subtree, and (2) The current node, so that we can process it after the traversal of the right subtree. To simulate this, we can use two separate stacks to store these two nodes.
We declare two separate stacks: rightStack to store the right child and mainStack to store the current node. We also initialize an extra pointer, currNode, to track the current node during the traversal. Now we run a loop until either the mainStack is empty or currNode is not equal to NULL.
If currNode != NULL: If the right child of the currNode is not NULL, we push the right child into the rightStack. Now we push the currNode into the mainStack and go to the left child. We continue the same process until we reach the leftmost end of the tree, i.e., currNode == NULL.
If currNode == NULL: We need to move to the parent of currNode, which is at the top of mainStack. So, we access this topNode from mainStack.
void iterativePostorder(TreeNode root)
{
if(root == NULL)
return
stack<TreeNode> mainStack
stack<TreeNode> rightStack
TreeNode currNode = root
while(!mainStack.empty() || currNode != NULL)
{
if(currNode != NULL)
{
if(currNode->right != NULL)
rightStack.push(currNode->right)
mainStack.push(currNode)
currNode = currNode->left
}
else
{
TreeNode topNode = mainStack.top()
if(!rightStack.empty() && topNode->right == rightStack.top())
{
currNode = topNode->right
rightStack.pop()
}
else
{
process(topNode->data)
mainStack.pop()
}
}
}
}
Each node is pushed into and popped out of the mainStack only once. Similarly, in the worst case, each node is pushed into the rightStack at most once. So we are doing a constant number of operations for each node. Time complexity = n * O(1) = O(n). We are using two different stacks, where the size of each stack depends on the height of the binary tree. So space complexity = O(h).
Can we optimize the above postorder traversal idea using a single stack? If we observe closely, we're using the rightStack solely to confirm whether the traversal of the right subtree of the mainStack top node (topNode) is complete. So, how can we eliminate the need for the rightStack? Here's an idea. Suppose we keep track of the prevNode during the traversal.
In this way, we can perform an iterative postorder traversal using a single stack while keeping track of the previously visited node using the prevNode pointer.
void iterativePostorderOptimized(TreeNode root)
{
if(root == NULL)
return
stack<TreeNode> mainStack
TreeNode currNode = NULL
TreeNode prevNode = NULL
while(mainStack.empty() == false || currNode != NULL)
{
if(currNode != NULL)
{
mainStack.push(currNode)
currNode = currNode->left
}
else
{
TreeNode topNode = mainStack.top()
if(topNode->right != NULL && topNode->right != prevNode)
currNode = topNode->right
else
{
process(topNode->data)
prevNode = topNode
mainStack.pop()
}
}
}
}
void iterativePostorder(TreeNode root)
{
if(root == NULL)
return
stack<TreeNode> treeStack
HashSet<TreeNode> visited
TreeNode currNode = root
while(!treeStack.empty() || currNode != NULL)
{
if(currNode != NULL)
{
if(visited.search(currNode) == true)
{
process(currNode-data)
currNode = NULL
}
else
{
treeStack.push(currNode)
if(currNode->right != NULL)
treeStack.push(currNode->right)
visited.insert(currNode)
currNode = currNode->left
}
}
else
{
currNode = treeStack.top()
treeStack.pop()
}
}
}
If you have any queries or feedback, please write us at contact@enjoyalgorithms.com. Enjoy learning, Enjoy algorithms!