diff --git a/C_CPP/DSA/Binary Tree/Zigzag_Traversal_Binary_Tree.md b/C_CPP/DSA/Binary Tree/Zigzag_Traversal_Binary_Tree.md new file mode 100644 index 0000000000..abf0ef8c0b --- /dev/null +++ b/C_CPP/DSA/Binary Tree/Zigzag_Traversal_Binary_Tree.md @@ -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 +#include +#include +using namespace std; + +struct Node { + int data; + Node* left; + Node* right; + + Node(int val) { + data = val; + left = right = NULL; + } +}; + +vector zigzagTraversal(Node* root) { + vector result; + if (root == NULL) + return result; + + queue q; + q.push(root); + bool leftToRight = true; + + while (!q.empty()) { + int size = q.size(); + vector 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 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