📜  逐行逐级遍历|第 3 组(使用一个队列)

📅  最后修改于: 2022-05-13 01:57:18.059000             🧑  作者: Mango

逐行逐级遍历|第 3 组(使用一个队列)

给定一棵二叉树,逐层打印节点,每一层都换行。

例子

Output:
1
2 3
4 5

我们在下面的文章中讨论了两种解决方案。
逐行打印层级顺序遍历 |设置 1
逐行逐级遍历| Set 2(使用两个队列)
在这篇文章中,讨论了一种使用一个队列的不同方法。首先将根元素和一个空元素插入队列。此空元素充当分隔符。接下来,从队列顶部弹出并将其左右节点添加到队列末尾,然后在队列顶部打印。继续这个过程,直到队列变空。

C++
/* C++ program to print levels 
line by line */
#include 
using namespace std;
  
// A Binary Tree Node
struct node
{
    struct node *left;
    int data;
    struct node *right;
};
  
// Function to do level order
// traversal line by line
void levelOrder(node *root)
{
    if (root == NULL) return;
  
    // Create an empty queue for
    // level order traversal
    queue q;
      
    // to store front element of 
    // queue.
    node *curr;
  
    // Enqueue Root and NULL node.
    q.push(root);
    q.push(NULL);
  
    while (q.size() > 1)
    {
        curr = q.front();
        q.pop();
          
        // condition to check 
        // occurrence of next 
        // level.
        if (curr == NULL)
        {
           q.push(NULL);
           cout << "\n";
        }
          
        else {
              
            // pushing left child of 
            // current node.
            if(curr->left)
            q.push(curr->left);
              
            // pushing right child of
            // current node.
            if(curr->right)
            q.push(curr->right);
              
            cout << curr->data << " ";
        }
    }
}
  
// Utility function to create a
// new tree node
node* newNode(int data)
{
    node *temp = new node;
    temp->data = data;
    temp->left = NULL;
    temp->right = NULL;
    return temp;
}
  
// Driver program to test above
// functions
int main()
{
      
    // Let us create binary tree
    // shown above
    node *root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    root->right->right = newNode(6);
  
    levelOrder(root);
    return 0;
}
  
// This code is contributed by
// Nikhil Jindal.


Java
// Java program to do level order
// traversal line by line
import java.util.LinkedList;
import java.util.Queue;
  
public class GFG {
  static class Node {
    int data;
    Node left;
    Node right;
  
    Node(int data) {
      this.data = data;
      left = null;
      right = null;
    }
  }
  
  // Prints level order traversal line
  // by line using two queues.
  static void levelOrder(Node root) {
    if (root == null)
      return;
  
    Queue q = new LinkedList<>();
  
    // Pushing root node into the queue.
    q.add(root);
  
    // Pushing delimiter into the queue.
    q.add(null);
  
    // Executing loop till queue becomes
    // empty
    while (!q.isEmpty()) {
  
      Node curr = q.poll();
  
      // condition to check the
      // occurence of next level
      if (curr == null) {
        if (!q.isEmpty()) {
          q.add(null);
          System.out.println();
        }
      } else {
        // Pushing left child current node
        if (curr.left != null)
          q.add(curr.left);
  
        // Pushing right child current node
        if (curr.right != null)
          q.add(curr.right);
  
        System.out.print(curr.data + " ");
      }
    }
  }
  
  // Driver function
  public static void main(String[] args) {
  
    Node root = new Node(1);
    root.left = new Node(2);
    root.right = new Node(3);
    root.left.left = new Node(4);
    root.left.right = new Node(5);
    root.right.right = new Node(6);
  
    levelOrder(root);
  }
}
  
// This code is Contributed by Rishabh Jindal


Python3
# Python3 program to print levels
# line by line 
from collections import deque as queue
  
# A Binary Tree Node
class Node:
      
    def __init__(self, key):
          
        self.data = key
        self.left = None
        self.right = None
  
# Function to do level order
# traversal line by line
def levelOrder(root):
      
    if (root == None):
        return
  
    # Create an empty queue for
    # level order traversal
    q = queue()
  
    # To store front element of
    # queue.
    #node *curr
  
    # Enqueue Root and None node.
    q.append(root)
    q.append(None)
  
    while (len(q) > 1):
        curr = q.popleft()
        #q.pop()
  
        # Condition to check
        # occurrence of next
        # level.
        if (curr == None):
           q.append(None)
           print()
  
        else:
  
            # Pushing left child of
            # current node.
            if (curr.left):
                q.append(curr.left)
  
            # Pushing right child of
            # current node.
            if (curr.right):
                q.append(curr.right)
  
            print(curr.data, end = " ")
              
# Driver code
if __name__ == '__main__':
      
    # Let us create binary tree
    # shown above
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)
    root.right.right = Node(6)
  
    levelOrder(root)
  
# This code is contributed by mohit kumar 29


C#
// C# program to do level order
// traversal line by line
using System;
using System.Collections;
  
class GFG 
{
public class Node 
{
    public int data;
    public Node left;
    public Node right;
  
    public Node(int data) 
    {
        this.data = data;
        left = null;
        right = null;
    }
}
  
// Prints level order traversal line
// by line using two queues.
static void levelOrder(Node root) 
{
    if (root == null)
    return;
  
    Queue q = new Queue();
  
    // Pushing root node into the queue.
    q.Enqueue(root);
  
    // Pushing delimiter into the queue.
    q.Enqueue(null);
  
    // Executing loop till queue becomes
    // empty
    while (q.Count>0)
    {
  
        Node curr = (Node)q.Peek();
        q.Dequeue();
  
        // condition to check the
        // occurence of next level
        if (curr == null) 
        {
            if (q.Count > 0)
            {
                q.Enqueue(null);
                 Console.WriteLine();
            }
        } 
        else 
        {
            // Pushing left child current node
            if (curr.left != null)
            q.Enqueue(curr.left);
      
            // Pushing right child current node
            if (curr.right != null)
            q.Enqueue(curr.right);
      
            Console.Write(curr.data + " ");
        }
    }
}
  
// Driver code
static public void Main(String []args) 
{
  
    Node root = new Node(1);
    root.left = new Node(2);
    root.right = new Node(3);
    root.left.left = new Node(4);
    root.left.right = new Node(5);
    root.right.right = new Node(6);
  
    levelOrder(root);
}
}
  
// This code is Contributed by Arnab Kundu


Javascript


输出 :

1
2 3
4 5 6

时间复杂度: O(n)