Zigzag Traversal of a Binary Tree - Iterative Approach
Visualization Player
Problem Statement
Examples
Solution
Algorithm Steps
Code
C
C++
Python
Java
JS
Go
Rust
Kotlin
TS
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
TreeNode* createNode(int val) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = node->right = NULL;
return node;
}
void zigzagTraversal(TreeNode* root) {
if (!root) return;
TreeNode* currentStack[100];
TreeNode* nextStack[100];
int top1 = -1, top2 = -1;
int leftToRight = 1;
currentStack[++top1] = root;
while (top1 >= 0) {
while (top1 >= 0) {
TreeNode* node = currentStack[top1--];
printf("%d ", node->val);
if (leftToRight) {
if (node->left) nextStack[++top2] = node->left;
if (node->right) nextStack[++top2] = node->right;
} else {
if (node->right) nextStack[++top2] = node->right;
if (node->left) nextStack[++top2] = node->left;
}
}
printf("\n");
TreeNode** temp = currentStack;
memcpy(currentStack, nextStack, sizeof(nextStack));
top1 = top2;
top2 = -1;
leftToRight = !leftToRight;
}
}
int main() {
TreeNode* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
zigzagTraversal(root);
return 0;
}
Comments
Loading comments...