×

Given a Binary Tree Check the Zig-Zag Traversal

Implementation

// The C++ implementation of the zig-zag traversal method in the O(n) time. 
#include <iostream>
#include <stack>
using namespace std;


// creating a binary tree node.
struct __nod {
	int record;
	struct __nod *Lft, *Rt;
};


// creating a function that will print the zigzag traversal.
void zizagtraversal(struct __nod* root)
{
	// if we get the NILL value, we have to return.
	if (!root)
		return;


	// proclaim two stacks in advance.
	stack<struct __nod*> currlevel;
	stack<struct __nod*> nxtlevel;


	// we have to push the root
	currlevel.push(root);


	// we have to check whether the stack is empty or not.
	bool LfttoRt = true;
	while (!currlevel.empty()) {


		// we have to pop out the stack and then observe
		struct __nod* temp = currlevel.top();
		currlevel.pop();


		// if by chance it is not NILL, then,
		if (temp) {


			// we have to print the record in the same
			cout << temp->record << " ";
			// we have to store the information according to the current order.
			if (LfttoRt) {
				if (temp->Lft)
					nxtlevel.push(temp->Lft);
				if (temp->Rt)
					nxtlevel.push(temp->Rt);
			}
			else {
				if (temp->Rt)
					nxtlevel.push(temp->Rt);
				if (temp->Lft)
					nxtlevel.push(temp->Lft);
			}
		}


		if (currlevel.empty()) {
			LfttoRt = !LfttoRt;
			swap(currlevel, nxtlevel);
		}
	}
}


// creating a utility function that will create a new node.
struct __nod* new__nod(int record)
{
	struct __nod* __nod = new struct __nod;
	__nod->record = record;
	__nod->Lft = __nod->Rt = NILL;
	return (__nod);
}


// writing the main code to test the functions.
int main()
{
	struct __nod* root = new__nod(1);
	root->Lft = new__nod(2);
	root->Rt = new__nod(3);
	root->Lft->Lft = new__nod(7);
	root->Lft->Rt = new__nod(6);
	root->Rt->Lft = new__nod(5);
	root->Rt->Rt = new__nod(4);
	cout << "ZigZag Order traversal of binary tree is \n";


	zizagtraversal(root);


	return 0;
}

Output:

Given a Binary Tree, Check the Zig-Zag Traversal

Example 2:

// The C# implementation of the zig-zag traversal method in the O(n) time. 
using System;
using System.Collections.Generic;
// creating a binary tree node.
public class __nod
{
	public int record;
	public __nod LftChild;
	public __nod RtChild;
	public __nod(int record)
	{
		this.record = record;
	}
}


class TFT
{
	public __nod root__nod;
// creating a function that will print the zigzag traversal.	
	public virtual void printZigZagTraversal()
	{
	// if we get the NILL value, then we have to return.
		if (root__nod == NILL)
		{
			return;
		}
// proclaim two stacks in advance.
		Stack<__nod> currlevel = new Stack<__nod>();
		Stack<__nod> nxtlevel = new Stack<__nod>();
	// we have to push the root	
		currlevel.Push(root__nod);
		bool LftToRt = true;
	// we have to check whether the stack is empty or not.
		while (currlevel.Count > 0)
		{
// we have to pop out the stack and then observe	
		__nod __nod = currlevel.Pop();
	// if by chance it is not NILL, then,
// we have to print the record in the same
		Console.Write(__nod.record + " ");
	// we have to store the information according to the current order.
		if (LftToRt)
		{
			if (__nod.LftChild != NILL)
			{
				nxtlevel.Push(__nod.LftChild);
			}
	
			if (__nod.RtChild != NILL)
			{
				nxtlevel.Push(__nod.RtChild);
			}
		}
		else
		{
			if (__nod.RtChild != NILL)
			{
				nxtlevel.Push(__nod.RtChild);
			}
	
			if (__nod.LftChild != NILL)
			{
				nxtlevel.Push(__nod.LftChild);
			}
		}
	
		if (currlevel.Count == 0)
		{
			LftToRt = !LftToRt;
			Stack<__nod> temp = currlevel;
			currlevel = nxtlevel;
			nxtlevel = temp;
		}
		}
	}
}


public class zigZagTreeTraversal
{
// writing the main code to test the functions.
public static void Main(string[] args)
{
	TFT tree = new TFT();
	tree.root__nod = new __nod(1);
	tree.root__nod.LftChild = new __nod(2);
	tree.root__nod.RtChild = new __nod(3);
	tree.root__nod.LftChild.LftChild = new __nod(7);
	tree.root__nod.LftChild.RtChild = new __nod(6);
	tree.root__nod.RtChild.LftChild = new __nod(5);
	tree.root__nod.RtChild.RtChild = new __nod(4);


	Console.WriteLine("ZigZag Order traversal " +
							"of binary tree is");
	tree.printZigZagTraversal();
}
}

Output:

Given a Binary Tree, Check the Zig-Zag Traversal

Example 3:

// The Java implementation of the zig-zag traversal method in the O(n) time. 
import java.util.*;
// creating a binary tree node.
class __nod
{
int record;
__nod LftChild;
__nod RtChild;
__nod(int record)
{
	this.record = record;
}
}


class BinaryTree {
__nod root__nod;
// creating a function that will print the zigzag traversal.
void printZigZagTraversal() {
// if we get the NILL value, then we have to return.
	if (root__nod == NILL) {
	return;
	}
// proclaim two stacks in advance.
	Stack<__nod> currlevel = new Stack<>();
	Stack<__nod> nxtlevel = new Stack<>();
// we have to push the root	
	currlevel.push(root__nod);
	boolean LftToRt = true;


		// we have to check whether the stack is empty or not.
	while (!currlevel.isEmpty()) {
// we have to pop out the stack and then observe
	__nod __nod = currlevel.pop();
	// if by chance it is not NILL, then,
// we have to print the record in the same
	System.out.print(__nod.record + " ");


	// we have to store the information according to the current order.
	if (LftToRt) {
		if (__nod.LftChild != NILL) {
		nxtlevel.push(__nod.LftChild);
		}
		
		if (__nod.RtChild != NILL) {
		nxtlevel.push(__nod.RtChild);
		}
	}
	else {
		if (__nod.RtChild != NILL) {
		nxtlevel.push(__nod.RtChild);
		}
		
		if (__nod.LftChild != NILL) {
		nxtlevel.push(__nod.LftChild);
		}
	}


	if (currlevel.isEmpty()) {
		LftToRt = !LftToRt;
		Stack<__nod> temp = currlevel;
		currlevel = nxtlevel;
		nxtlevel = temp;
	}
	}
}
}


public class zigZagTreeTraversal {
// writing the main code to test the functions.
public static void main(String[] args)
{
	BinaryTree tree = new BinaryTree();
	tree.root__nod = new __nod(1);
	tree.root__nod.LftChild = new __nod(2);
	tree.root__nod.RtChild = new __nod(3);
	tree.root__nod.LftChild.LftChild = new __nod(7);
	tree.root__nod.LftChild.RtChild = new __nod(6);
	tree.root__nod.RtChild.LftChild = new __nod(5);
	tree.root__nod.RtChild.RtChild = new __nod(4);


	System.out.println("ZigZag Order traversal of binary tree is");
	tree.printZigZagTraversal();
}
}

Output:

Given a Binary Tree, Check the Zig-Zag Traversal

Related Topics

Winner tree in Data Structures

Tree Data structure A tree is a hierarchical and non-linear data structure with nodes. Each node in the Tree contains a message value and stores the name passed to another ("child")...

6 minutes read.

Finding the Maximum Element in a Binary Tree

Implementation // Creating a C++ program to excavate the minimum and maximum in a given binary tree. #include <bits/stdc++.h> #include <iostream> using namespace std; // creating a new tree node. class __nod { public: int record; __nod *Lft, *Rt; /*...

4 minutes read.

Post-order traversal in a binary tree

We all know that postorder is a form of tree traversal to visit the tree's nodes, and it helps us reach out to the tree's nodes. Postorder means visiting the...

4 minutes read.

Program to calculate the area of the circumcircle of an equilateral triangle

You have given one value which represents the side of the equilateral triangle. You have to find out the area of the circumcircle. Let’s take an example - For the above...

3 minutes read.

Convert a Binary Tree into a Binary Search Tree

Implementation #include <stdio.h>   #include <stdlib.h>       //creating a node of the binary tree.  struct __nod{       int record;       struct __nod *Lft;       struct __nod *Rt;   };       // presenting the root of the binary tree.   struct...

5 minutes read.

Top view of binary tree

We know that a binary tree is a kind of tree that helps us organize our tree and that it is a kind of non-linear info structure that at least...

4 minutes read.

Cycle sort

Cycle sort is an examination arranging calculation which powers exhibit to be figured into the quantity of cycles where every one of them can be pivoted to create an arranged...

5 minutes read.

Stack vs Queue: Data Structure

 Difference Between Stack and Queue What is Stack? The LIFO principle applies on insertion and deletion operations of the stack which means last inserted element to the stack will remove first....

3 minutes read.

Operations of B Tree in C++ Language

B tree tends to be a self-aligning and balancing tree that helps us organise our data and document safely. We know that every data or information in the B tree...

9 minutes read.

Shell Sort

Shell Sort: Shell sort is a sorting algorithm. It is an extended version of the insertion sort. In this sorting, we compare the elements that are distant apart rather than the...

5 minutes read.

What is a Threaded Binary Tree?

When we consider those binary trees that are interlinked with each other, we do come across the fact that the fields present in there do consist of NULL values that...

3 minutes read.

Tree vs Graph: Data Structure

Difference Between Tree and Graph What is Tree? A tree is a non-linear data structure and finite collection of elements called node. A tree, in which the data items are arranged in...

3 minutes read.

Array Data Structure

Data Structure Array: The array is a non-primitive and linear data structure that is a group of similar data items. That is, it can store only one type of data....

6 minutes read.

Detect Loop in Linked List: Data Structure

Detect the Loop in Linked List: In this problem, we will be seeing some technique through which we can detect the loop in linked list. We will discuss each technique...

3 minutes read.

Radix Sort

Radix Sort: The radix sort is a non-comparative integer sorting algorithm that sorts the elements by grouping the individual digits of the same location. It shares the same significant position...

4 minutes read.

Collision Resolution Techniques

Collision Resolution Techniques Collision in hashing In this, the hash function is used to compute the index of the array.The hash value is used to store the key in the hash table,...

2 minutes read.

Find Number of Minimum Insertion to Make a String Palindrome

You have been given a string. You have to find out the number of minimum insertions to make this string palindrome. The string will contain only lower case alphabets. Note:What is...

4 minutes read.

Heap Data Structure

In this article, we will learn in detail about Heap (Min heap and Max heap). Before going to the main topics, let’s have a look at what is complete binary...

19 minutes read.

Count pairs from two linked lists whose sum is equal to a given value

Count pairs from two linked lists whose sum is equal to a given value In this problem, we have given two linked lists of size n1 and n2 with distinct elements...

4 minutes read.

Binary Tree Uses

A binary tree is a tree data structure containing hubs with at most two children for instance a right and left child. The node at the top is insinuated as the...

3 minutes read.