树的顺序遍历
The level of a binary tree start from the root node with value 0. Every time we move down, we increase the level by one. There can be one or more nodes at a single level. You can see the diagram below :
二叉树的级别从值为0的根节点开始。每次向下移动时,级别都会增加1。 单个级别上可以有一个或多个节点。 您可以看到下图:
In level order traversal, we traverse the tree level wise. First level 0 will be traversed then 1 and so on. If we write level order traversal for the above diagram we get, A B C D E F G.
在级别顺序遍历中,我们明智地遍历树。 首先遍历0级,然后遍历1,依此类推。 如果我们为上面的图编写级别顺序遍历,则得到ABCDEFG。
Level order traversal of a tree is breadth-first traversal for the tree.
树的级别顺序遍历是树的广度优先遍历 。
Algorithm for level order traversal :
级别顺序遍历的算法:
We use a queue for implementing level order traversal. For each node, first, the node is visited, and then its children are enqueued. First, we create a queue and enqueue the root. Then we will run a loop while the queue is not empty and do the following steps:
我们使用一个队列来实现级别顺序遍历。 对于每个节点,首先访问该节点,然后将其子节点排队。 首先,我们创建一个队列并排队入根。 然后,当队列不为空时,我们将运行一个循环并执行以下步骤:
- Print the data of the node. 打印节点的数据。
- Enqueue its children. 使其子孙入队。
- Dequeue the node. 使节点出队。
Let’s see the implementation i