×

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

Binary search tree traversal in-order pre-order post-order examples

A binary search tree is a type of non-linear tree in which the tree contains at least two nods. It is called binary because of its nature that states bi...

8 minutes read.

Circular Linked List

Circular Linked List A circular linked list where all nodes are connected to their next node and last node is connected to the starting node or we can say all nodes...

5 minutes read.

Lowest common ancestor in a binary search tree

Suppose you have given two values of nodes in a binary search tree. You have to find out the lowest common ancestor between the nodes. Let’s take an example tree- For the...

4 minutes read.

Sum of Nodes in a Binary Tree

In this article, we will see the sample problems that will help us understand the concept and summation of all the nodes in the binary tree. Implementation /* creating a program that...

4 minutes read.

Linear vs Circular Queue: Data Structure

Difference Between Linear and Circular Queue What is Linear Queue? A linear queue is linear data structure which works on first in first out principle. We can say a linear queue is...

3 minutes read.

B+ Tree Program in Q language

A B+ tree is just an improvised version of a self-balancing and well-maintained tree in which all the key values that hold valuable information is present at the bottom, which...

9 minutes read.

Function to Insert a Node in a Binary Search Tree

Implementation // writing C++ code that will help us in implementing the insertion operation in a binary search tree. #include <bits/stdc++.h> using namespace std; // creating a new binary search tree node struct __nod { int...

8 minutes read.

Length of longest palindrome in a linked list using O(1) extra space

Length of longest palindrome in a linked list using O(1) extra space In this problem, we need to find the length of the longest palindrome list that is present in given...

2 minutes read.

Tree terminology in Data structures

Data structures The storage used to organize and store data is known as a data structure, and it is a method where data can be arranged on a computer to be...

6 minutes read.

Find Bridges in a Graph

You have been given a graph. You have to find out the bridges in that graph. Graph may be connected or disconnected. You have to print vertices of particular edge...

4 minutes read.

Deletion Operation of the binary search tree in C++ language

A typical binary search tree implements some order to carry out the arrangements. As the name suggests, each parent node should have at most two children. The main rule in...

4 minutes read.

What is a Height-Balanced Tree in Data Structure

A height-balanced tree is a type of binary tree. If the absolute difference between the heights of the left and right subtree is less than or equal to 1, then...

6 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.

Convert binary tree to a doubly linked list

Implementation //creating a C++ program for the transition of a binary tree into a linked list. #include <iostream> using namespace std; /* Firstly, let’s create a binary tree that will help us in setting...

4 minutes read.

Adding one to the number represented an array of digits

You have given one array, which consists of values which represent the different digits of a number. You have to add 1 to this number and store the result in...

3 minutes read.

Data structure: Infix to Prefix Conversion

Infix to Prefix Conversion In present time, we use the infix expression in our daily life but the computers are not able to understand this format because they need to keep...

4 minutes read.

Time Complexity of Selection Sort in Data Structure

What is Time Complexity? The term “Time complexity” can be defined as the number of times executions made of a particular sequence of instructions and not the total amount of time...

3 minutes read.

Binary Search Tree

Binary Search Tree: A binary search tree is a type of tree in which every node is organized in the sorted order. It is also called an ordered binary tree. Properties...

4 minutes read.

What are Forest Trees in Data Structure

Data structure A data model manages and optimizes computer resources, and a database stores and manages data. It's one of many uses for data structures to hold data. Data structures come...

5 minutes read.

Horizontal and Vertical Scaling

Being a software engineer, you would have designed a website or application and deployed it on any server. Imagine that the developed application starts getting popular, and many users engage...

6 minutes read.