Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
146 changes: 146 additions & 0 deletions C_CPP/DSA/Binary Tree/Zigzag_Traversal_Binary_Tree.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
# Zigzag Traversal of Binary Tree

## Overview

Zigzag traversal (also called **spiral traversal**) is a level-order traversal technique for a binary tree where the direction of traversal alternates at each level.

* Level 0: Left to Right
* Level 1: Right to Left
* Level 2: Left to Right
* and so on...

This traversal is useful when a non-linear, alternating view of tree levels is required.

---

## Example

Consider the following binary tree:

```
1
/ \
2 3
/ \ / \
4 5 6 7
```

**Zigzag Traversal Output:**

```
1 3 2 4 5 6 7
```

Explanation:

* Level 0 β†’ `1` (Left to Right)
* Level 1 β†’ `3 2` (Right to Left)
* Level 2 β†’ `4 5 6 7` (Left to Right)

---

## Algorithm

1. Use a **queue** to perform level-order traversal.
2. Maintain a boolean flag `leftToRight` to track traversal direction.
3. For each level:

* Store node values in a temporary vector.
* Reverse the vector if `leftToRight` is `false`.
4. Append the values to the result.
5. Toggle the `leftToRight` flag after each level.

---

## C++ Implementation

```cpp
#include <iostream>
#include <queue>
#include <vector>
using namespace std;

struct Node {
int data;
Node* left;
Node* right;

Node(int val) {
data = val;
left = right = NULL;
}
};

vector<int> zigzagTraversal(Node* root) {
vector<int> result;
if (root == NULL)
return result;

queue<Node*> q;
q.push(root);
bool leftToRight = true;

while (!q.empty()) {
int size = q.size();
vector<int> level(size);

for (int i = 0; i < size; i++) {
Node* temp = q.front();
q.pop();

int index = leftToRight ? i : size - i - 1;
level[index] = temp->data;

if (temp->left)
q.push(temp->left);
if (temp->right)
q.push(temp->right);
}

for (int val : level)
result.push_back(val);

leftToRight = !leftToRight;
}

return result;
}

int main() {
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->left = new Node(6);
root->right->right = new Node(7);

vector<int> output = zigzagTraversal(root);

for (int val : output)
cout << val << " ";

return 0;
}
```

---

## Time and Space Complexity

* **Time Complexity:** `O(n)` β€” each node is visited once.
* **Space Complexity:** `O(n)` β€” queue and result storage.

---

## Notes

* Zigzag traversal is applicable to **any binary tree**, not limited to Binary Search Trees.
* This approach avoids explicit vector reversal by calculating indices based on direction.

---

## References

* Level Order Traversal
* Binary Tree Basics