Zig-Zag traversal of a Binary Tree using Recursion
Last Updated :
25 Sep, 2024
Given a binary tree, the task is to find the zigzag level order traversal of the tree. In zig zag traversal starting from the first level go from left to right for odd-numbered levels and right to left for even-numbered levels.
Approach:
The zigzag traversal of a binary tree involves traversing the tree in level order manner while alternating the direction of traversal at each level. For each level, if the direction is from left to right, we begin by recursively traversing the left subtree before moving to the right subtree. Conversely, if the direction is from right to left, we start by traversing the right subtree first, followed by the left subtree. This approach ensures that the nodes are traversed in the zigzag order.
Step-by-step implementation:
- Find the height of the tree 'h'. Initialize a boolean variable leftToRight (initially set to true).
- Traverse each level i from 1 to h, do the following:
- Recursively traverse the tree, starting from the root by calling leftToRightTrav or RightToLeftTrav function based on the boolean variable leftToRight.
- if leftToRight is true call leftToRightTrav function to traverse for left subtree first then right subtree, otherwise call for RightToLeftTrav function to traverse for right subtree first then left subtree.
- Flip the value of leftToRight.
Below is the implementation of the above approach:
C++
// C++ Program to traverse a binary
// tree in zigzag manner.
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *left;
Node *right;
Node(int x) {
data = x;
left = nullptr;
right = nullptr;
}
};
// Function to calculate height of tree
int treeHeight(Node *root){
if(!root) return 0;
int lHeight = treeHeight(root->left);
int rHeight = treeHeight(root->right);
return max(lHeight, rHeight) + 1;
}
// Function which prints from left to right
void leftToRightTrav(Node* root, int level, vector<int>&ans) {
if (root == nullptr) return;
if (level == 1) {
ans.push_back(root->data);
}
else {
leftToRightTrav(root->left, level-1, ans);
leftToRightTrav(root->right, level-1, ans);
}
}
// Function which prints from right to left
void rightToLeftTrav(Node* root, int level, vector<int>&ans) {
if (root == nullptr) return;
if (level == 1) {
ans.push_back(root->data);
}
else {
rightToLeftTrav(root->right, level-1, ans);
rightToLeftTrav(root->left, level-1, ans);
}
}
// Function to traverse tree in zig zag order
vector<int> zigZagTraversal(Node* root) {
vector<int> ans;
bool leftToRight = true;
int height = treeHeight(root);
// Traverse the tree by height
for(int i = 1; i <= height; i++){
if (leftToRight)
leftToRightTrav(root, i, ans);
else
rightToLeftTrav(root, i, ans);
// Flip the value of leftToRight
leftToRight = !leftToRight;
}
return ans;
}
void printList(vector<int> v) {
int n = v.size();
for (int i=0; i<n; i++) {
cout << v[i] << " ";
}
cout << endl;
}
int main() {
// Create a hard coded tree.
// 20
// / \
// 8 22
// / \ \
// 4 12 11
// / \
// 10 14
Node* root = new Node(20);
root->left = new Node(8);
root->right = new Node(22);
root->right->right = new Node(11);
root->left->left = new Node(4);
root->left->right = new Node(12);
root->left->right->left = new Node(10);
root->left->right->right = new Node(14);
vector<int> ans = zigZagTraversal(root);
printList(ans);
return 0;
}
C
// C code to traverse a binary tree in zigzag manner
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Function to calculate height of the tree
int treeHeight(struct Node* root) {
if (root == NULL) return 0;
int lHeight = treeHeight(root->left);
int rHeight = treeHeight(root->right);
return (lHeight > rHeight ? lHeight : rHeight) + 1;
}
// Function to traverse from left to right
void leftToRightTrav(struct Node* root, int level, int* ans, int* index) {
if (root == NULL) return;
if (level == 1) {
ans[(*index)++] = root->data;
} else {
leftToRightTrav(root->left, level - 1, ans, index);
leftToRightTrav(root->right, level - 1, ans, index);
}
}
// Function to traverse from right to left
void rightToLeftTrav(struct Node* root, int level, int* ans, int* index) {
if (root == NULL) return;
if (level == 1) {
ans[(*index)++] = root->data;
} else {
rightToLeftTrav(root->right, level - 1, ans, index);
rightToLeftTrav(root->left, level - 1, ans, index);
}
}
// Function to traverse the tree in zigzag order
void zigZagTraversal(struct Node* root, int* ans, int* size) {
bool leftToRight = true;
int height = treeHeight(root);
int index = 0;
for (int i = 1; i <= height; i++) {
if (leftToRight)
leftToRightTrav(root, i, ans, &index);
else
rightToLeftTrav(root, i, ans, &index);
leftToRight = !leftToRight;
}
// Set the size of the result
*size = index;
}
struct Node* createNode(int val) {
struct Node* node =
(struct Node*)malloc(sizeof(struct Node));
node->data = val;
node->left = node->right = NULL;
return node;
}
int main() {
// Create a hard coded tree.
// 20
// / \
// 8 22
// / \ \
// 4 12 11
// / \
// 10 14
struct Node* root = createNode(20);
root->left = createNode(8);
root->right = createNode(22);
root->right->right = createNode(11);
root->left->left = createNode(4);
root->left->right = createNode(12);
root->left->right->left = createNode(10);
root->left->right->right = createNode(14);
// Array to hold zigzag traversal results
int ans[200];
int size = 0;
zigZagTraversal(root, ans, &size);
for (int i = 0; i < size; i++) {
printf("%d ", ans[i]);
}
printf("\n");
return 0;
}
Java
// Java Program to traverse a
// binary tree in zigzag manner
import java.util.ArrayList;
import java.util.List;
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = right = null;
}
}
class GfG {
// Function to calculate height of tree
static int treeHeight(Node root) {
if (root == null) return 0;
int lHeight = treeHeight(root.left);
int rHeight = treeHeight(root.right);
return Math.max(lHeight, rHeight) + 1;
}
// Function which prints from left to right
static void leftToRightTrav(Node root, int level, ArrayList<Integer> ans) {
if (root == null) return;
if (level == 1) {
ans.add(root.data);
} else {
leftToRightTrav(root.left, level - 1, ans);
leftToRightTrav(root.right, level - 1, ans);
}
}
// Function which prints from right to left
static void rightToLeftTrav(Node root, int level, ArrayList<Integer> ans) {
if (root == null) return;
if (level == 1) {
ans.add(root.data);
} else {
rightToLeftTrav(root.right, level - 1, ans);
rightToLeftTrav(root.left, level - 1, ans);
}
}
// Function to traverse tree in zigzag order
static ArrayList<Integer> zigZagTraversal(Node root) {
ArrayList<Integer> ans = new ArrayList<>();
boolean leftToRight = true;
int height = treeHeight(root);
// Traverse the tree by height
for (int i = 1; i <= height; i++) {
if (leftToRight)
leftToRightTrav(root, i, ans);
else
rightToLeftTrav(root, i, ans);
// Flip the value of leftToRight
leftToRight = !leftToRight;
}
return ans;
}
static void printList(List<Integer> v) {
for (int i : v) {
System.out.print(i + " ");
}
System.out.println();
}
public static void main(String[] args) {
// Create a hard coded tree.
// 20
// / \
// 8 22
// / \ \
// 4 12 11
// / \
// 10 14
Node root = new Node(20);
root.left = new Node(8);
root.right = new Node(22);
root.right.right = new Node(11);
root.left.left = new Node(4);
root.left.right = new Node(12);
root.left.right.left = new Node(10);
root.left.right.right = new Node(14);
ArrayList<Integer> ans = zigZagTraversal(root);
printList(ans);
}
}
Python
# Python Program to traverse
# a binary tree in zigzag manner
class Node:
def __init__(self, x):
self.data = x
self.left = None
self.right = None
# Function to calculate height of tree
def treeHeight(root):
if root is None:
return 0
lHeight = treeHeight(root.left)
rHeight = treeHeight(root.right)
return max(lHeight, rHeight) + 1
# Function which prints from left to right
def leftToRightTrav(root, level, ans):
if root is None:
return
if level == 1:
ans.append(root.data)
else:
leftToRightTrav(root.left, level - 1, ans)
leftToRightTrav(root.right, level - 1, ans)
# Function which prints from right to left
def rightToLeftTrav(root, level, ans):
if root is None:
return
if level == 1:
ans.append(root.data)
else:
rightToLeftTrav(root.right, level - 1, ans)
rightToLeftTrav(root.left, level - 1, ans)
# Function to traverse tree in zigzag order
def zigZagTraversal(root):
ans = []
leftToRight = True
height = treeHeight(root)
# Traverse the tree by height
for i in range(1, height + 1):
if leftToRight:
leftToRightTrav(root, i, ans)
else:
rightToLeftTrav(root, i, ans)
# Flip the value of leftToRight
leftToRight = not leftToRight
return ans
def printList(v):
for i in v:
print(i, end=" ")
print()
if __name__ == "__main__":
# Create a hard coded tree.
# 20
# / \
# 8 22
# / \ \
# 4 12 11
# / \
# 10 14
root = Node(20)
root.left = Node(8)
root.right = Node(22)
root.right.right = Node(11)
root.left.left = Node(4)
root.left.right = Node(12)
root.left.right.left = Node(10)
root.left.right.right = Node(14)
ans = zigZagTraversal(root)
printList(ans)
C#
// C# Program to traverse a
// binary tree in zigzag manner
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node(int x) {
data = x;
left = right = null;
}
}
class GfG {
// Function to calculate height of tree
static int TreeHeight(Node root) {
if (root == null) return 0;
int lHeight = TreeHeight(root.left);
int rHeight = TreeHeight(root.right);
return Math.Max(lHeight, rHeight) + 1;
}
// Function which prints from left to right
static void LeftToRightTrav(Node root, int level, List<int> ans) {
if (root == null) return;
if (level == 1) {
ans.Add(root.data);
} else {
LeftToRightTrav(root.left, level - 1, ans);
LeftToRightTrav(root.right, level - 1, ans);
}
}
// Function which prints from right to left
static void RightToLeftTrav(Node root, int level, List<int> ans) {
if (root == null) return;
if (level == 1) {
ans.Add(root.data);
} else {
RightToLeftTrav(root.right, level - 1, ans);
RightToLeftTrav(root.left, level - 1, ans);
}
}
// Function to traverse tree in zigzag order
static List<int> zigZagTraversal(Node root) {
List<int> ans = new List<int>();
bool leftToRight = true;
int height = TreeHeight(root);
// Traverse the tree by height
for (int i = 1; i <= height; i++) {
if (leftToRight)
LeftToRightTrav(root, i, ans);
else
RightToLeftTrav(root, i, ans);
// Flip the value of leftToRight
leftToRight = !leftToRight;
}
return ans;
}
static void PrintList(List<int> v) {
foreach (int i in v) {
Console.Write(i + " ");
}
Console.WriteLine();
}
static void Main() {
// Create a hard coded tree.
// 20
// / \
// 8 22
// / \ \
// 4 12 11
// / \
// 10 14
Node root = new Node(20);
root.left = new Node(8);
root.right = new Node(22);
root.right.right = new Node(11);
root.left.left = new Node(4);
root.left.right = new Node(12);
root.left.right.left = new Node(10);
root.left.right.right = new Node(14);
List<int> ans = zigZagTraversal(root);
PrintList(ans);
}
}
JavaScript
// JavaScript Program to traverse
// a binary tree in zigzag manner
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
// Function to calculate height of tree
function treeHeight(root) {
if (root === null) return 0;
let lHeight = treeHeight(root.left);
let rHeight = treeHeight(root.right);
return Math.max(lHeight, rHeight) + 1;
}
// Function which prints from left to right
function leftToRightTrav(root, level, ans) {
if (root === null) return;
if (level === 1) {
ans.push(root.data);
} else {
leftToRightTrav(root.left, level - 1, ans);
leftToRightTrav(root.right, level - 1, ans);
}
}
// Function which prints from right to left
function rightToLeftTrav(root, level, ans) {
if (root === null) return;
if (level === 1) {
ans.push(root.data);
} else {
rightToLeftTrav(root.right, level - 1, ans);
rightToLeftTrav(root.left, level - 1, ans);
}
}
// Function to traverse tree in zigzag order
function zigZagTraversal(root) {
let ans = [];
let leftToRight = true;
let height = treeHeight(root);
// Traverse the tree by height
for (let i = 1; i <= height; i++) {
if (leftToRight) {
leftToRightTrav(root, i, ans);
} else {
rightToLeftTrav(root, i, ans);
}
// Flip the value of leftToRight
leftToRight = !leftToRight;
}
return ans;
}
function printList(v) {
v.forEach(i => console.log(i));
}
// Create a hard coded tree.
// 20
// / \
// 8 22
// / \ \
// 4 12 11
// / \
// 10 14
let root = new Node(20);
root.left = new Node(8);
root.right = new Node(22);
root.right.right = new Node(11);
root.left.left = new Node(4);
root.left.right = new Node(12);
root.left.right.left = new Node(10);
root.left.right.right = new Node(14);
let ans = zigZagTraversal(root);
printList(ans);
Output20 22 8 4 12 11 14 10
Time Complexity: O(n*h), where n is the number of nodes and h is the height of the tree.
Auxiliary Space: O(h)
Note: This approach may get time limit exceeded(TLE) error as it is not an optimized approach. For optimized approach, Please refer to ZigZag Tree Traversal
Similar Reads
Zig Zag Level order traversal of a tree using single array Write a function to print spiral order traversal of a tree. For below tree, function should print 1, 2, 3, 4, 5, 6, 7. We have discussed naive approach and two stack based approach in Level Order with recursion and multiple stacksThe idea behind this approach is first we have to take a queue, a dire
9 min read
Flatten Binary Tree in order of Zig Zag traversal Given a Binary Tree, the task is to flatten it in order of ZigZag traversal of the tree. In the flattened binary tree, the left node of all the nodes must be NULL.Examples: Input: 1 / \ 5 2 / \ / \ 6 4 9 3 Output: 1 2 5 6 4 9 3 Input: 1 \ 2 \ 3 \ 4 \ 5 Output: 1 2 3 4 5 Approach: We will solve this
7 min read
Clockwise Spiral Traversal of Binary Tree | Set - 2 Given a Binary Tree. The task is to print the circular clockwise spiral order traversal of the given binary tree.Examples: Input : 1 / \ 2 3 / \ \ 4 5 6 / / \ 7 8 9 Output :1 9 8 7 2 3 6 5 4 Input : 20 / \ 8 22 / \ / \ 5 3 4 25 / \ 10 14 Output :20 14 10 8 22 25 4 3 5 We have already discussed Clock
11 min read
Iterative Boundary Traversal of Complete Binary tree Given a complete binary tree, the task is to traverse it such that all the boundary nodes are visited in Anti-Clockwise order starting from the root.Example: Input: Output: 1 2 4 5 6 7 3 Input: Output: 18 15 40 50 100 20 30Approach:Traverse left-most nodes of the tree from top to down. (Left boundar
9 min read
Print nodes in top view of Binary Tree | Set 2 Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Given a binary tree, print the top view of it. The output nodes should be printed from left to right. Note: A node x is there in output if x is the topmost node at its horizontal distance. Horizontal distance
14 min read