使用 C++ 中的单个队列实现之字形层次遍历树
在此问题中,给出了一个二叉树。我们的任务是打印树的之字形层次遍历。对于此遍历,我们将只使用一个队列。
让我们举个例子来理解这个问题,
输出 −
3 1 7 2 8 9 5
要使用单个队列解决此问题,我们将使用额外的分离标记以及队列和方向标记。
现在,我们将逐级遍历树,插入根元素,现在为队列的每个元素插入其子节点。如果遇到 NULL,我们将检查方向,然后按照给定的方向遍历元素。然后,我们将继续插入,直到访问最后一个 NULL。
示例
程序说明我们的解决方案,
#include <bits/stdc++.h> using namespace std; struct Node { int data; struct Node *left, *right; }; struct Node* insertNode(int data) { struct Node* node = new struct Node; node->data = data; node->left = node->right = NULL; return (node); } void zigZagTraversal(struct Node* root, int n){ struct Node* queue[2 * n]; int top = -1; int front = 1; queue[++top] = NULL; queue[++top] = root; queue[++top] = NULL; int prevFront = 0, count = 1; while (1) { struct Node* curr = queue[front]; if (curr == NULL) { if (front == top) break; else { if (count % 2 == 0) { for (int i = prevFront + 1; i < front; i++) cout<<queue[i]->data<<"\t"; } else { for (int i = front - 1; i > prevFront; i--) cout<<queue[i]->data<<"\t"; } prevFront = front; count++; front++; queue[++top] = NULL; continue; } } if (curr->left != NULL) queue[++top] = curr->left; if (curr->right != NULL) queue[++top] = curr->right; front++; } if (count % 2 == 0) { for (int i = prevFront + 1; i < top; i++) cout<<queue[i]->data<<"\t"; } else { for (int i = top - 1; i > prevFront; i--) cout<<queue[i]->data<<"\t"; } } int main() { struct Node* root = insertNode(3); root->left = insertNode(1); root->right = insertNode(7); root->left->left = insertNode(5); root->left->right = insertNode(9); root->right->left = insertNode(8); root->right->right = insertNode(2); cout<<"Zig Zag traversal of the tree is :\n"; zigZagTraversal(root, 7); return 0; }
输出
Zig Zag traversal of the tree is : 3 1 7 2 8 9 5
广告