📌  相关文章
📜  打印二叉树每个级别的中间节点

📅  最后修改于: 2021-05-06 23:16:12             🧑  作者: Mango

给定二叉树,任务是打印二叉树的每个级别的中间节点。将M视为任何级别的节点数,如果M为奇数,则打印第(M / 2)节点。否则,打印第(M / 2)节点和第((M / 2)+1)节点。

例子:

方法:想法是在给定的Tree上执行DFS遍历,并将每个级别的所有节点存储在向量映射中。现在遍历地图并相应地打印中间节点。步骤如下:

  1. 初始化向量M的映射,以将与每个级别相对应的所有节点存储在向量中。
  2. 级别0开始对给定的树执行DFS遍历,然后递归调用级别为1的左右子树。
  3. 将上述DFS遍历中与每个级别相对应的所有节点存储为M [level] .push_back(root-> data)
  4. 现在,遍历地图M,并针对每个级别执行以下操作:
    • 在地图M中找到与每个级别关联的向量(例如A )的大小(例如S )。
    • 如果S为奇数,则只需将A [(S – 1)/ 2]的值打印为第(S / 2)中间节点。
    • 别的打印A [(S – 1)/ 2]的值和A [(S – 1)/ 2 + 1]作为中间(S / 2)((S / 2)+ 1) 节点。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Structure Node of Binary Tree
struct node {
    int data;
    struct node* left;
    struct node* right;
};
 
// Function to create a new node
struct node* newnode(int d)
{
    struct node* temp
        = (struct node*)malloc(
            sizeof(struct node));
    temp->data = d;
    temp->left = NULL;
    temp->right = NULL;
 
    // Return the created node
    return temp;
}
 
// Function that performs the DFS
// traversal on Tree to store all the
// nodes at each level in map M
void dfs(node* root, int l,
         map >& M)
{
    // Base Case
    if (root == NULL)
        return;
 
    // Push the current level node
    M[l].push_back(root->data);
 
    // Left Recursion
    dfs(root->left, l + 1, M);
 
    // Right Recursion
    dfs(root->right, l + 1, M);
}
 
// Function that print all the middle
// nodes for each level in Binary Tree
void printMidNodes(node* root)
{
 
    // Stores all node in each level
    map > M;
 
    // Perform DFS traversal
    dfs(root, 0, M);
 
    // Traverse the map M
    for (auto& it : M) {
 
        // Get the size of vector
        int size = it.second.size();
 
        // For odd number of elements
        if (size & 1) {
 
            // Print (M/2)th Element
            cout << it.second[(size - 1) / 2]
                 << endl;
        }
 
        // Otherwise
        else {
 
            // Print (M/2)th and
            // (M/2 + 1)th Element
            cout << it.second[(size - 1) / 2]
                 << ' '
                 << it.second[(size - 1) / 2 + 1]
                 << endl;
        }
    }
}
 
// Driver Code
int main()
{
    /*
    Binary tree shown below is:
  
                                1
                              /   \
                            2      3
                          /   \   /  \
                         4     5 10   8
                              / \
                             11  6
                                / \
                               7   9
  
  
    */
 
    // Given Tree
    struct node* root = newnode(1);
    root->left = newnode(2);
    root->right = newnode(3);
    root->left->left = newnode(4);
    root->left->right = newnode(5);
    root->left->right->left = newnode(11);
    root->left->right->right = newnode(6);
    root->left->right->right->left = newnode(7);
    root->left->right->right->right = newnode(9);
    root->right->left = newnode(10);
    root->right->right = newnode(8);
 
    // Function Call
    printMidNodes(root);
 
    return 0;
}


Java
// Java program for
// the above approach
import java.util.*;
class GFG{
   
static Map > M;
 
// Structure Node of
// Binary Tree
static class node
{
  int data;
  node left;
  node right;
  public node() {}
  public node(int data,
              node left,
              node right)
  {
    super();
    this.data = data;
    this.left = left;
    this.right = right;
  }
};
 
// Function to create a new node
static node newnode(int d)
{
  node temp = new node();
  temp.data = d;
  temp.left = null;
  temp.right = null;
 
  // Return the created node
  return temp;
}
 
// Function that performs the DFS
// traversal on Tree to store all the
// nodes at each level in map M
static void dfs(node root, int l)
{
  // Base Case
  if (root == null)
    return;
 
  // Push the current level node
  if(!M.containsKey(l))
  {
    Vector temp = new Vector();
    temp.add(root.data);
    M.put(l, temp);
  }
  else
    M.get(l).add(root.data);
 
  // Left Recursion
  dfs(root.left, l + 1);
 
  // Right Recursion
  dfs(root.right, l + 1);
}
 
// Function that print all the middle
// nodes for each level in Binary Tree
static void printMidNodes(node root)
{
  // Stores all node in each level
  M = new HashMap >();
   
  // Perform DFS traversal
  dfs(root, 0);
 
  // Traverse the map M
  for (Map.Entry> it : M.entrySet())
  {
    // Get the size of vector
    int size = it.getValue().size();
 
    // For odd number of elements
    if (size % 2 == 1)
    {
      // Print (M/2)th Element
      System.out.print(it.getValue().get((size - 1) / 2) + "\n");
    }
 
    // Otherwise
    else
    {
      // Print (M/2)th and
      // (M/2 + 1)th Element
      System.out.print(it.getValue().get((size - 1) / 2) + " " +
                       it.getValue().get(((size - 1) / 2) + 1) + "\n");
    }
  }
}
 
// Driver Code
public static void main(String[] args)
{
  /*
    Binary tree shown below is:
 
                                1
                              /   \
                            2      3
                          /   \   /  \
                         4     5 10   8
                              / \
                             11  6
                                / \
                               7   9
 
 
    */
 
  // Given Tree
  node root = newnode(1);
  root.left = newnode(2);
  root.right = newnode(3);
  root.left.left = newnode(4);
  root.left.right = newnode(5);
  root.left.right.left = newnode(11);
  root.left.right.right = newnode(6);
  root.left.right.right.left = newnode(7);
  root.left.right.right.right = newnode(9);
  root.right.left = newnode(10);
  root.right.right = newnode(8);
 
  // Function Call
  printMidNodes(root);
}
}
 
//This code is contributed by 29AjayKumar


Python3
# Python3 program for the above approach
  
# Structure Node of Binary Tree
class node:
 
    def __init__(self, data):
         
        self.data = data
        self.left = None
        self.right = None
 
# Function to create a new node
def newnode(d):
 
    temp = node(d)
  
    # Return the created node
    return temp
  
# Function that performs the DFS
# traversal on Tree to store all the
# nodes at each level in map M
def dfs(root, l, M):
 
    # Base Case
    if (root == None):
        return
  
    # Push the current level node
    if l not in M:
        M[l] = []
         
    M[l].append(root.data)
  
    # Left Recursion
    dfs(root.left, l + 1, M)
  
    # Right Recursion
    dfs(root.right, l + 1, M)
 
# Function that print all the middle
# nodes for each level in Binary Tree
def printMidNodes(root):
  
    # Stores all node in each level
    M = dict()
  
    # Perform DFS traversal
    dfs(root, 0, M)
  
    # Traverse the map M
    for it in M.values():
  
        # Get the size of vector
        size = len(it)
  
        # For odd number of elements
        if (size & 1):
  
            # Print (M/2)th Element
            print(it[(size - 1) // 2])
  
        # Otherwise
        else:
  
            # Print (M/2)th and
            # (M/2 + 1)th Element
            print(str(it[(size - 1) // 2]) + ' ' +
                  str(it[(size - 1) // 2 + 1]))
  
# Driver Code
if __name__=="__main__":
 
    '''
    Binary tree shown below is:
            1
          /   \
        2      3
      /   \   /  \
     4     5 10   8
          / \
         11  6
            / \
           7   9
    '''
     
    # Given Tree
    root = newnode(1)
    root.left = newnode(2)
    root.right = newnode(3)
    root.left.left = newnode(4)
    root.left.right = newnode(5)
    root.left.right.left = newnode(11)
    root.left.right.right = newnode(6)
    root.left.right.right.left = newnode(7)
    root.left.right.right.right = newnode(9)
    root.right.left = newnode(10)
    root.right.right = newnode(8)
  
    # Function Call
    printMidNodes(root)
  
# This code is contributed by rutvik_56


C#
// C# program for
// the above approach
using System;
using System.Collections;
using System.Collections.Generic;
 
class GFG{
    
static Dictionary M;
  
// Structure Node of
// Binary Tree
class node
{
  public int data;
  public node left;
  public node right;
  public node(int data,
              node left,
              node right)
  {
    this.data = data;
    this.left = left;
    this.right = right;
  }
};
  
// Function to create a new node
static node newnode(int d)
{
  node temp = new node(d, null, null);
  
  // Return the created node
  return temp;
}
  
// Function that performs the DFS
// traversal on Tree to store all the
// nodes at each level in map M
static void dfs(node root, int l)
{
  // Base Case
  if (root == null)
    return;
  
  // Push the current level node
  if(!M.ContainsKey(l))
  {
    ArrayList temp = new ArrayList();
    temp.Add(root.data);
    M[l] = temp;
  }
  else
    M[l].Add(root.data);
  
  // Left Recursion
  dfs(root.left, l + 1);
  
  // Right Recursion
  dfs(root.right, l + 1);
}
  
// Function that print all the middle
// nodes for each level in Binary Tree
static void printMidNodes(node root)
{
  // Stores all node in each level
  M = new Dictionary();
    
  // Perform DFS traversal
  dfs(root, 0);
  
  // Traverse the map M
  foreach (KeyValuePair it in M)
  {
    // Get the size of vector
    int size = it.Value.Count;
  
    // For odd number of elements
    if (size % 2 == 1)
    {
      // Print (M/2)th Element
      Console.Write(it.Value[(size - 1) / 2] + "\n");
    }
  
    // Otherwise
    else
    {
       
      // Print (M/2)th and
      // (M/2 + 1)th Element
      Console.Write(it.Value[(size - 1) / 2] + " " +
                       it.Value[((size - 1) / 2) + 1] + "\n");
    }
  }
}
  
// Driver Code
public static void Main(string[] args)
{
  /*
    Binary tree shown below is:
  
                                1
                              /   \
                            2      3
                          /   \   /  \
                         4     5 10   8
                              / \
                             11  6
                                / \
                               7   9
  
  
    */
  
  // Given Tree
  node root = newnode(1);
  root.left = newnode(2);
  root.right = newnode(3);
  root.left.left = newnode(4);
  root.left.right = newnode(5);
  root.left.right.left = newnode(11);
  root.left.right.right = newnode(6);
  root.left.right.right.left = newnode(7);
  root.left.right.right.right = newnode(9);
  root.right.left = newnode(10);
  root.right.right = newnode(8);
  
  // Function Call
  printMidNodes(root);
}
}
 
// This code is contributed by pratham76


输出:
1
2 3
5 10
11 6
7 9

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