Construct a Binary Tree from Inorder and Postorder Traversal iteratively.
I've seen how to do it with recursion, but I'm looking for an answer that constructs the binary tree iteratively.
I wrote an algorithm for inorder and preorder, but I'm wondering how to modify it for inorder and postorder?
Note: It's in pseudocode and "=" means "=="
Node:
e: TElement
right: PNode (pointer to a Node)
left: PNode (pointer to a Node)
Binary Tree:
root: PNode
Subalgorithm tree(preorder, inorder)
pre: preorder: Int[], inorder: Int[]
preOrderIndex<- 0;
inOrderIndex<-0;
Stack(s)
root <- createNode(preorder[0])
push(s, root)
preOrderIndex<-preOrderIndex +1
While !empty(s)
element(s, top) //which is the same as top = peak(s)
if [top].e = inorder[inOrderIndex]
delete(s, top) //delete the element from the stack
inOrderIndex<-inOrderIndex +1
if inOrderIndex = length(inorder)
return root
End if
element(s, elem)
if !empty(s) and [elem].e = inorder[inOrderIndex]
continue
End if
nod <- createNode(preorder[preOrderIndex])
[top].right<-nod
preOrderIndex<-preOrderIndex +1
push(s,nod)
Else
nod <- createNode(preorder[preOrderIndex])
[top].left<-nod
preOrderIndex<-preOrderIndex +1
push(s,nod)
End if
End while
return root
End Subalgorithm
Edit: I've found the answer