Learn-dsa..in 30 days!



























CC-8 : Traverse Binary Tree via In-order/ Depth First traversal.

Description:

As part of In-order (also known as DepthFirst) all nodes are iteratively/ recursively traversed in order of left node, parent node, right node. Given an input Binary Tree, traverse the tree in In-order.

Test cases and expected outputs:

Input Parameters Expected outputs

InOrder traversal :
33, 6, 5, 78, 4, 8, 14, 9, 18 ,16, 7

Pseudocode:

Initialize an ArrayList to hold the result of the In-order traversal.
Initialize a Stack to temporarily hold Tree Nodes that are being processed in LIFO order.
Initialize current node variable to root of input Binary Tree.
Iterate through stack nodes using an endless while loop:
If current node is not null, add the current node to the stack. Update current node to point to its own left child.
Else :
If stack size is empty, we have traversed the whole tree, so exit the while loop.
Set current node to first node of the Stack.
Add current node’s node data to In-order traversal ArrayList.
Update current node to point to its own right child.
Return In-order traversal ArrayList.


Code:

public ArrayList<Integer> inOrderIterative(BinTreeNode root) throws Exception{
	if (root==null) {return null;}
	ArrayList<Integer> inOrder=new ArrayList<Integer>();
	Deque<BinTreeNode> stack=new LinkedList<BinTreeNode>();
	BinTreeNode node=root;
	while (true) {
		if (node != null) {
			stack.offerFirst(node);
			node=node.getLeftChild();
		}else {
			if (stack.size()==0) {
				break;
			}
			node=stack.pollFirst();
			inOrder.add(node.getNodeData());
			node=node.getRightChild();
		}
	}
		
	return inOrder;
}

Click here to download and run code and test cases !