Learn-dsa..in 30 days!



























CC-13 : Traverse Binary Tree via Post-order using recursion.

Description:

As part of Post-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 recursively.

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.

Method postOrderRecursive(parentNode):

If parentNode is null, return.
Call postOrderRecursive() with parent node’s left child as parameter.
Call postOrderRecursive() with parent node’s right child as parameter.
Add parent node’s node data to Post-order traversal ArrayList.


Code:

public class BinTreePostOrderRecursive {

private ArrayList<Integer> postOrder=new ArrayList<Integer>();
public ArrayList<Integer> getPostOrder() {
	return postOrder;
}
public void setPostOrder(ArrayList<Integer> postOrder) {
	this.postOrder = postOrder;
}

public void postOrderRecursive(BinTreeNode parent) throws Exception{
	if (parent==null) {return;}
	postOrderRecursive(parent.getLeftChild());
	postOrderRecursive(parent.getRightChild());
	postOrder.add(parent.getNodeData());
}
}

Click here to download and run code and test cases !