📌  相关文章
📜  从二叉树的所有级别打印备用节点

📅  最后修改于: 2021-05-04 21:13:08             🧑  作者: Mango

给定一棵二叉树,任务是从左到右遍历给定二叉树的每个级别,并打印在该级别遇到的每个替代项。

例子:

方法:可以通过在给定的二叉树上执行Level Order Traversal遍历来解决该问题。请按照以下步骤解决问题:

  1. 初始化一个队列,以存储给定二叉树的每个级别的节点。
  2. 执行级别顺序遍历并从二叉树的每个级别打印备用节点

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Structure of a Node
struct Node {
    int data;
    Node* left;
    Node* right;
    Node(int val)
    {
        data = val;
        left = right = NULL;
    }
};
 
// Print alternate nodes of
// a binary tree
void PrintAlternate(Node* root)
{
    // Store nodes of each level
    queue Q;
    Q.push(root);
 
    while (!Q.empty()) {
        // Store count of nodes
        // of current level
        int N = Q.size();
 
        // Print alternate nodes of
        // the current level
        for (int i = 0; i < N; i++) {
            Node* temp = Q.front();
            Q.pop();
 
            if (i % 2 == 0) {
                cout << temp->data << " ";
            }
 
            // If left child exists
            if (temp->left) {
                // Store left child
                Q.push(temp->left);
            }
 
            // If right child exists
            if (temp->right) {
                // Store right child
                Q.push(temp->right);
            }
        }
        cout << endl;
    }
}
 
// Driver Code
int main()
{
    Node* root;
 
    // Create a tree
    root = new Node(71);
    root->left = new Node(88);
    root->right = new Node(99);
    root->left->left = new Node(4);
    root->left->right = new Node(5);
    root->right->left = new Node(6);
    root->right->right = new Node(7);
    root->left->left->left = new Node(8);
    root->left->left->right = new Node(9);
    root->left->right->left = new Node(10);
    root->left->right->right = new Node(11);
    root->right->left->right = new Node(13);
    root->right->right->left = new Node(14);
    PrintAlternate(root);
}


Java
// Java program to implement
// the above approach
import java.util.*;
class GFG{
 
// Structure of a Node
static class Node
{
  int data;
  Node left;
  Node right;
  Node(int val)
  {
    data = val;
    left = right = null;
  }
};
 
// Print alternate nodes of
// a binary tree
static void PrintAlternate(Node root)
{
  // Store nodes of each level
  Queue Q = new LinkedList<>();
  Q.add(root);
 
  while (!Q.isEmpty())
  {
    // Store count of nodes
    // of current level
    int N = Q.size();
 
    // Print alternate nodes of
    // the current level
    for (int i = 0; i < N; i++)
    {
      Node temp = Q.peek();
      Q.remove();
 
      if (i % 2 == 0)
      {
        System.out.print(temp.data + " ");
      }
 
      // If left child exists
      if (temp.left!=null)
      {
        // Store left child
        Q.add(temp.left);
      }
 
      // If right child exists
      if (temp.right!=null)
      {
        // Store right child
        Q.add(temp.right);
      }
    }
    System.out.println();
  }
}
 
// Driver Code
public static void main(String[] args)
{
  Node root;
 
  // Create a tree
  root = new Node(71);
  root.left = new Node(88);
  root.right = new Node(99);
  root.left.left = new Node(4);
  root.left.right = new Node(5);
  root.right.left = new Node(6);
  root.right.right = new Node(7);
  root.left.left.left = new Node(8);
  root.left.left.right = new Node(9);
  root.left.right.left = new Node(10);
  root.left.right.right = new Node(11);
  root.right.left.right = new Node(13);
  root.right.right.left = new Node(14);
  PrintAlternate(root);
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program to implement
# the above approach
 
# Structure of a Node
class newNode:
     
    def __init__(self, val):
         
        self.data = val
        self.left = None
        self.right = None
 
# Print alternate nodes of
# a binary tree
def PrintAlternate(root):
     
    # Store nodes of each level
    Q = []
    Q.append(root)
 
    while (len(Q)):
         
        # Store count of nodes
        # of current level
        N = len(Q)
 
        # Print alternate nodes of
        # the current level
        for i in range(N):
            temp = Q[0]
            Q.remove(Q[0])
 
            if (i % 2 == 0):
                print(temp.data, end = " ")
 
            # If left child exists
            if (temp.left):
                 
                # Store left child
                Q.append(temp.left)
 
            # If right child exists
            if (temp.right):
                 
                # Store right child
                Q.append(temp.right)
                 
        print("\n", end = "")
 
# Driver Code
if __name__ == '__main__':
     
    # Create a tree
    root = newNode(71)
    root.left = newNode(88)
    root.right = newNode(99)
    root.left.left = newNode(4)
    root.left.right = newNode(5)
    root.right.left = newNode(6)
    root.right.right = newNode(7)
    root.left.left.left = newNode(8)
    root.left.left.right = newNode(9)
    root.left.right.left = newNode(10)
    root.left.right.right = newNode(11)
    root.right.left.right = newNode(13)
    root.right.right.left = newNode(14)
     
    PrintAlternate(root)
 
# This code is contributed by ipg2016107


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Structure of a Node
class Node
{
  public int data;
  public Node left;
  public Node right;
  public Node(int val)
  {
    data = val;
    left = right = null;
  }
};
 
// Print alternate nodes of
// a binary tree
static void PrintAlternate(Node root)
{
  // Store nodes of each level
  Queue Q = new Queue();
  Q.Enqueue(root);
 
  while (Q.Count != 0)
  {
    // Store count of nodes
    // of current level
    int N = Q.Count;
 
    // Print alternate nodes of
    // the current level
    for (int i = 0; i < N; i++)
    {
      Node temp = Q.Peek();
      Q.Dequeue();
 
      if (i % 2 == 0)
      {
        Console.Write(temp.data + " ");
      }
 
      // If left child exists
      if (temp.left!=null)
      {
        // Store left child
        Q.Enqueue(temp.left);
      }
 
      // If right child exists
      if (temp.right!=null)
      {
        // Store right child
        Q.Enqueue(temp.right);
      }
    }
    Console.WriteLine();
  }
}
 
// Driver Code
public static void Main(String[] args)
{
  Node root;
 
  // Create a tree
  root = new Node(71);
  root.left = new Node(88);
  root.right = new Node(99);
  root.left.left = new Node(4);
  root.left.right = new Node(5);
  root.right.left = new Node(6);
  root.right.right = new Node(7);
  root.left.left.left = new Node(8);
  root.left.left.right = new Node(9);
  root.left.right.left = new Node(10);
  root.left.right.right = new Node(11);
  root.right.left.right = new Node(13);
  root.right.right.left = new Node(14);
  PrintAlternate(root);
}
}
 
// This code is contributed by 29AjayKumar


输出:
71 
88 
4 6 
8 10 13










时间复杂度: O(N)
辅助空间: O(N)