spiral traversal of binary tree

This can be done using two stacks in iterative manner.

The below diagram depicts the spiral traversal of BST
SpriralBST

Steps to solve
push level_1 nodes (i.e, only root node) into stack_1;
next by popping elements of level_1, push children of level_l in to stack_2 (i.e, level_2);
next by popping elements of level_2, push children of level_2 in to stack_2 (i.e, level_3);
… so on

Code:

	/**
	 * Algorithm to print binary tree in spiral manner
	 * 
	 * @param node root node of the binary tree
	 */
	public void printTreeInSpiralForm(BinaryNode node) {
		Stack<BinaryNode> stack1 = new Stack<BinaryNode>();
		Stack<BinaryNode> stack2 = new Stack<BinaryNode>();
		stack1.push(node);

		while (!stack1.empty() || !stack2.empty()) {
			//
			while (!stack1.empty()) {
				node = stack1.pop();
				if(node != null) {
					System.out.print(node.element+", ");
					if(node.left != null)
						stack2.push(node.left);
					if(node.right != null)
						stack2.push(node.right);
				}
			}

			while (!stack2.empty() && node != null) {
				node = stack2.pop();
				if(node != null) {
					System.out.print(node.element+", ");
					if(node.left != null)
						stack1.push(node.right);
					if(node.right != null)
						stack1.push(node.left);
				}
			}
		}
	}

Output:
20, 25, 15, 12, 18, 22, 28, 32, 26, 24, 21, 19, 17, 14, 6

Mawazo

Mostly technology with occasional sprinkling of other random thoughts

amintabar

Amir Amintabar's personal page

101 Books

Reading my way through Time Magazine's 100 Greatest Novels since 1923 (plus Ulysses)

Seek, Plunnge and more...

My words, my world...

ARRM Foundation

Do not wait for leaders; do it alone, person to person - Mother Teresa

Executive Management

An unexamined life is not worth living – Socrates

javaproffesionals

A topnotch WordPress.com site

thehandwritinganalyst

Just another WordPress.com site

coding algorithms

"An approximate answer to the right problem is worth a good deal more than an exact answer to an approximate problem." -- John Tukey

%d bloggers like this: