CC-12 : Traverse Binary Tree via Post-order.
Description:
As part of Pre-order all nodes are iteratively/ recursively traversed in order of left node, right node, parent node. Given an input Binary Tree, traverse the tree in Post-order iteratively.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| PostOrder traversal : 33 ,6 ,78 ,5 ,8 ,9 ,18 ,16 ,14 ,7 ,4 |
Pseudocode:
| Initialize an ArrayList to hold the result of the Post-order traversal. |
| Initialize a Stack to temporarily hold Tree Nodes that are being processed in LIFO order. |
| Assign root node reference to currentNode variable . |
| Iterate through stack nodes using an while loop, while Stack size is not zero and the currentNode is not null:
If the currentNode is not null, add it to the Stack. Set currentNode’s left child reference to currentNode.
Else:
Assign right child of first node of stack to a variable named right.
if right is null:
Extract first node of stack to a variable named top.
Extract first node of stack to a variable named top.
Add node data of top to Post-order traversal ArrayList.
While stack size is not zero and top is same as right child of first node/top most node of stack:
Extract firstnode of stack to a variable named top.
Add node data of top to Post-order traversal ArrayList.
If the parentNode’s left childs not null, add it the left child node to the Stack.
|
| Return Post-order traversal ArrayList. |
Code:
public ArrayList<Integer> postOrderIterative(BinTreeNode root) throws Exception{
if (root==null) {return null;}
ArrayList<Integer> postOrder=new ArrayList<Integer>();
Deque<BinTreeNode> stack=new LinkedList<BinTreeNode>();
BinTreeNode node=root;
while ((node !=null)||(stack.size() !=0)) {
if (node != null) {
stack.offerFirst(node);
node=node.getLeftChild();
}else {
BinTreeNode right=stack.peekFirst().getRightChild();
BinTreeNode top=null;
if (right==null) {
top=stack.pollFirst();
postOrder.add(top.getNodeData());
while ((stack.size() !=0)&&(top==stack.peekFirst().getRightChild())) {
top=stack.pollFirst();
postOrder.add(top.getNodeData());
}
}else {
node=right;
}
}
}
return postOrder;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |