在本教程中,我们将看到如何逐层打印树节点。
问题陈述:
给定树的根节点,逐级打印节点。
例如:
考虑下面的树:
这里的级别顺序遍历如下:
[一种]
[b,c]
[d,e,f,g]
即我们需要逐级打印节点。
级别顺序遍历也可以编写如下:
a,b,c,d,e,f,g
即没有逐级打印,而是单行打印。
我们可以借助队列解决此问题。
基本思路:
步骤1:使节点入队
步骤2:使节点出队并打印
步骤3:使节点的左右子节点入队。
现在,应用这些步骤并检查我们的结果。
首先使根节点入队
现在将节点“ a”移至输出,将其标记为已访问。插入节点“ a”的左右子节点。
现在选择节点“ b”将其移动到输出。然后将其子级插入队列。
现在选择节点“ c”将其移动到输出。将其左右两个孩子插入队列。
同样,如果执行相同的操作,则会得到结果。
现在让我们看看如何逐级打印:
我们遵循以下步骤:
步骤1:将根加入队列
步骤2:将Null排入队列
步骤3:将节点出队并返回null
步骤4:让左右孩子入队
步骤5:如果元素为null,则,
- 转到下一行
- 使null入队。
现在,通过示例来看一下上述步骤:
最初,我们插入根节点“ a”,然后插入null。
现在,将a出队到输出向量。
如图所示插入左右孩子,将其标记为已访问。
请注意,到目前为止,我们位于第一行。
现在,使NULL出队,因此当我们使null出队时,我们转到下一行并将NULL插入到数组中。
现在,在接下来的2次迭代中,我们打印b,插入其子项d,e,然后打印c,然后插入其子项f,g。
现在我们到达NULL,我们转到下一行并将NULL插入队列。
最后我们得到如下结果:
C ++解决方案
#include <iostream> #include <queue> using namespace std; // structure to hold binary tree node struct Node { int data; Node *left, *right; Node(int data) { this->data = data; this->left = this->right = nullptr; } }; void display_level_order(Node *root) { // Base Case if (root == NULL) return; queue<Node *> q; // Enqueue Root and initialize height q.push(root); while (q.empty() == false) { // display front of queue and remove it from queue Node *node = q.front(); cout << node->data << " "; q.pop(); // Enqueue left child if (node->left != NULL) q.push(node->left); // Enqueue right child if (node->right != NULL) q.push(node->right); } } int main() { Node* root = nullptr; /* Binary tree: 16 / \ / \ 10 25 / \ / \ / \ / \ 7 15 18 30 */ root = new Node(16); root->left = new Node(10); root->right = new Node(25); root->left->left = new Node(7); root->left->right = new Node(15); root->right->left = new Node(18); root->right->right = new Node(30); int level = 2; cout<<"Solution = " <<endl; display_level_order(root); return 0; }
输出:
Solution = 16 10 25 7 15 18 30
该网站上可用的教程列表:
C编程20+章 | C ++编程80+章 |
100多个编码问题 | 数据结构和算法85+章 |
系统设计20+章 | Shell脚本编写12章 |
4g LTE 60+章节 | 最常见的编码问题 |
5G NR 50+章 | Linux系统编程20+章 |