以升序打印 C++ 中二叉树等级
在此问题中,给定一棵二叉树,我们需要打印按其值升序排列的每一层的节点。
我们举个例子来更好地理解这个概念:
输入 −
输出 −
20 6 15 2 17 32 78
为了解决这个问题,我们需要打印树的每一层的升序。为此,我们需要创建一个队列和两个优先级队列。NULL 分隔符用于分隔两层。
示例
演示逻辑的程序 −
#include <iostream> #include <queue> #include <vector> using namespace std; struct Node { int data; struct Node *left, *right; }; void printLevelElements(Node* root){ if (root == NULL) return; queue<Node*> q; priority_queue<int, vector<int>, greater<int> > current_level; priority_queue<int, vector<int>, greater<int> > next_level; q.push(root); q.push(NULL); current_level.push(root->data); while (q.empty() == false) { int data = current_level.top(); Node* node = q.front(); if (node == NULL) { q.pop(); if (q.empty()) break; q.push(NULL); cout << "\n"; current_level.swap(next_level); continue; } cout << data << " "; q.pop(); current_level.pop(); if (node->left != NULL) { q.push(node->left); next_level.push(node->left->data); } if (node->right != NULL) { q.push(node->right); next_level.push(node->right->data); } } } Node* insertNode(int data){ Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp; } int main(){ Node* root = insertNode(12); root->left = insertNode(98); root->right = insertNode(34); root->left->left = insertNode(76); root->left->right = insertNode(5); root->right->left = insertNode(12); root->right->right = insertNode(45); cout << "Elements at each Level of binary tree are \n"; printLevelElements(root); return 0; }
输出
Elements at each Level of binary tree are 12 34 98 5 12 45 76
广告