Learn-dsa..in 30 days!



























CC-10 : Traverse Binary Tree via Pre-order.

Description:

As part of Pre-order all nodes are iteratively/ recursively traversed in order of parent node, left node, right node. Given an input Binary Tree, traverse the tree in Pre-order.

Test cases and expected outputs:

Input Parameters Expected outputs

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

Pseudocode:

Initialize an ArrayList to hold the result of the Pre-order traversal.
Initialize a Stack to temporarily hold Tree Nodes that are being processed in LIFO order.
Add the root node of Binary Tree to the Stack.
Iterate through stack nodes using an while loop, while Stack size is not zero:
Extract the first node of stack and assign it to a variable named parentNode.
Add parentNode’s node data to Pre-order traversal ArrayList.
If the parentNode’s right childs not null, add it the right child node to the Stack.
If the parentNode’s left childs not null, add it the left child node to the Stack.
Return Pre-order traversal ArrayList.


Code:

public ArrayList<Integer> preOrderIterative(BinTreeNode root) throws Exception{
	if (root==null) {return null;}
	ArrayList<Integer> preOrder=new ArrayList<Integer>();
	Deque<BinTreeNode> stack=new LinkedList<BinTreeNode>();
	stack.offerFirst(root);
	BinTreeNode parent=null;
	while (stack.size()!=0) {
		parent=stack.pollFirst();
		preOrder.add(parent.getNodeData());
		if (parent.getRightChild()!=null) {
			stack.offerFirst(parent.getRightChild());
		}
		if (parent.getLeftChild()!=null) {
			stack.offerFirst(parent.getLeftChild());
		}		
	}
	return preOrder;
}

Click here to download and run code and test cases !