Обход влево-вправо по всем уровням двоичного дерева
Опубликовано: 5 Января, 2022
        Учитывая двоичное дерево с корнем в узле 1, задача состоит в том, чтобы распечатать элементы в следующем определенном порядке.
- Во-первых, распечатайте все элементы последнего уровня альтернативным способом, например, сначала вы распечатаете крайний левый элемент, а затем крайний правый элемент и продолжайте так, пока все элементы не будут пройдены на последнем уровне.
- Теперь проделайте то же самое с остальными уровнями.
Примеры:
 Вход:
            1
          / 
        2 3
      /  /
     4 5 6
Выход: 4 6 5 2 3 1
Объяснение:
Сначала распечатайте все элементы последнего 
уровень, который будет напечатан следующим образом: 4 6 5
Теперь дерево становится
       1
     / 
    2 3
    
Теперь напечатайте элементы как 2 3
Теперь дерево становится: 1
Вход:
        1
      / 
     2 3
Выход: 2 3 1 Рекомендуется: сначала попробуйте свой подход в {IDE}, прежде чем переходить к решению.
Подход :
- Выполните вызов bfs и сохраните все узлы, присутствующие на уровне i, в векторном массиве.
- Также следите за максимальным уровнем, достигнутым при вызове bfs.
- Теперь распечатайте желаемый узор, начиная с максимального уровня до 0.
Ниже представлена реализация описанного выше подхода:
C ++
| // C++ implementation// for the above approach#include <bits/stdc++.h>usingnamespacestd;constintsz = 1e5;intmaxLevel = 0;// Adjacency list// representation of the treevector<int> tree[sz + 1];// Boolean array to mark all the// vertices which are visitedboolvis[sz + 1];// Integer array to store// the level of each nodeintlevel[sz + 1];// Array of vector where ith index// stores all the nodes at level ivector<int> nodes[sz + 1];// Utility function to create an// edge between two verticesvoidaddEdge(inta,intb){    // Add a to b's list    tree[a].push_back(b);    // Add b to a's list    tree[b].push_back(a);}// Modified Breadth-First Functionvoidbfs(intnode){  // Create a queue of {child, parent}  queue<pair<int,int> > qu;  // Push root node in the front of  // the queue and mark as visited  qu.push({ node, 0 });  nodes[0].push_back(node);  vis[node] =true;  level[1] = 0;  while(!qu.empty()) {    pair<int,int> p = qu.front();    // Dequeue a vertex from queue    qu.pop();    vis[p.first] =true;    // Get all adjacent vertices of the dequeued    // vertex s. If any adjacent has not    // been visited then enqueue it    for(intchild : tree[p.first]) {        if(!vis[child]) {            qu.push({ child, p.first });            level[child] = level[p.first] + 1;            maxLevel = max(maxLevel, level[child]);            nodes[level[child]].push_back(child);        }    }  }}// Function to display// the patternvoiddisplay(){  for(inti = maxLevel; i >= 0; i--) {    intlen = nodes[i].size();    // Printing all nodes    // at given level    for(intj = 0; j < len / 2; j++) {        cout << nodes[i][j] <<" "<< nodes[i][len - 1 - j] <<" ";    }    // If count of nodes    // at level i is odd    // print remaining node    if(len % 2 == 1) {        cout << nodes[i][len / 2] <<" ";    }  }}// Driver codeintmain(){  // Number of vertices  intn = 6;  addEdge(1, 2);  addEdge(1, 3);  addEdge(2, 4);  addEdge(2, 5);  addEdge(3, 6);  // Calling modified bfs function  bfs(1);  display();  return0;} | 
Джава
| // Java implementation// for the above approachimportjava.util.*;@SuppressWarnings("unchecked")classGFG{ staticintsz =100000;staticintmaxLevel =0;  // Adjacency list// representation of the treestaticArrayList []tree =newArrayList[sz +1];  // boolean array to mark all the// vertices which are visitedstaticboolean[]vis =newboolean[sz +1];  // Integer array to store// the level of each nodestaticint[]level =newint[sz +1];  // Array of vector where ith index// stores all the nodes at level istaticArrayList []nodes =newArrayList[sz +1];  // Utility function to create an// edge between two verticesstaticvoidaddEdge(inta,intb){        // Add a to b's list    tree[a].add(b);      // Add b to a's list    tree[b].add(a);}staticclassPair{    intKey, Value;    Pair(intKey,intValue)    {        this.Key = Key;        this.Value = Value;    }}  // Modified Breadth-Key Functionstaticvoidbfs(intnode){        // Create a queue of {child, parent}    Queue<Pair> qu =newLinkedList<>();        // Push root node in the front of    // the queue and mark as visited    qu.add(newPair(node,0));    nodes[0].add(node);    vis[node] =true;    level[1] =0;         while(qu.size() !=0)    {        Pair p = qu.poll();                                                     // Dequeue a vertex from queue        vis[p.Key] =true;                 // Get all adjacent vertices of the dequeued        // vertex s. If any adjacent has not        // been visited then put it        for(intchild : (ArrayList<Integer>)tree[p.Key])        {            if(!vis[child])            {                qu.add(newPair(child, p.Key));                level[child] = level[p.Key] +1;                maxLevel = Math.max(maxLevel,                                    level[child]);                nodes[level[child]].add(child);            }        }    }}  // Function to display// the patternstaticvoiddisplay(){    for(inti = maxLevel; i >=0; i--)    {        intlen = nodes[i].size();                // Printing all nodes        // at given level        for(intj =0; j < len /2; j++)        {            System.out.print((int)nodes[i].get(j) +" "+                             (int)nodes[i].get(len -1- j) +                             " ");        }                 // If count of nodes        // at level i is odd        // print remaining node        if(len %2==1)        {            System.out.print(                (int)nodes[i].get(len /2) +" ");        }    }} // Driver codepublicstaticvoidmain(String[] args){    for(inti =0; i < sz +1; i++)    {        tree[i] =newArrayList();        nodes[i] =newArrayList();        vis[i] =false;        level[i] =0;    }         addEdge(1,2);    addEdge(1,3);    addEdge(2,4);    addEdge(2,5);    addEdge(3,6);         // Calling modified bfs function    bfs(1);         display();}}// This code is contributed by pratham76 | 
Python3
| # Python3 implementation# for the above approachfromcollectionsimportdequesz=10**5maxLevel=0# Adjacency list# representation of the treetree=[[]foriinrange(sz+1)]# Boolean array to mark all the# vertices which are visitedvis=[False]*(sz+1)# Integer array to store# the level of each nodelevel=[0]*(sz+1)# Array of vector where ith index# stores all the nodes at level inodes=[[]foriinrange(sz+1)]# Utility function to create an# edge between two verticesdefaddEdge(a, b):        globaltree        # Add a to b's list    tree[a].append(b)    # Add b to a's list    tree[b].append(a)# Modified Breadth-First Functiondefbfs(node):        globalmaxLevel        # Create a queue of {child, parent}    qu=deque()        # Push root node in the front of    # the queue and mark as visited    qu.append([node,0])    nodes[0].append(node)    vis[node]=True    level[1]=0    while(len(qu) >0):        p=qu.popleft()                # Dequeue a vertex from queue        # qu.pop()        vis[p[0]]=True        # Get all adjacent vertices of the dequeued        # vertex s. If any adjacent has not        # been visited then enqueue it        forchildintree[p[0]]:            if(notvis[child]):                qu.append([child, p[0]])                level[child]=level[p[0]]+1                maxLevel=max(maxLevel, level[child])                nodes[level[child]].append(child)# Function to display# the patterndefdisplay():    foriinrange(maxLevel,-1,-1):        lenn=len(nodes[i])                # Printing all nodes        # at given level        forjinrange(lenn//2):            print(nodes[i][j],                  nodes[i][lenn-1-j], end=" ")                    # If count of nodes        # at level i is odd        # prremaining node        if(lenn%2==1):            print(nodes[i][lenn//2], end=" ")# Driver codeif__name__=='__main__':    # Number of vertices    n=6    addEdge(1,2)    addEdge(1,3)    addEdge(2,4)    addEdge(2,5)    addEdge(3,6)        # Calling modified bfs function    bfs(1)    display()# This code is contributed by mohit kumar 29 | 
C #
| // C# implementation// for the above approachusingSystem;usingSystem.Collections.Generic;usingSystem.Collections;classGFG{staticintsz = 100000;staticintmaxLevel = 0; // Adjacency list// representation of the treestaticArrayList []tree =newArrayList[sz + 1]; // Boolean array to mark all the// vertices which are visitedstaticbool[]vis =newbool[sz + 1]; // Integer array to store// the level of each nodestaticint[]level =newint[sz + 1]; // Array of vector where ith index// stores all the nodes at level istaticArrayList []nodes =newArrayList[sz + 1]; // Utility function to create an// edge between two verticesstaticvoidaddEdge(inta,intb){        // Add a to b's list    tree[a].Add(b);     // Add b to a's list    tree[b].Add(a);} // Modified Breadth-First Functionstaticvoidbfs(intnode){        // Create a queue of {child, parent}    Queue qu =newQueue();        // Push root node in the front of    // the queue and mark as visited    qu.Enqueue(newKeyValuePair<int,int>(node, 0));    nodes[0].Add(node);    vis[node] =true;    level[1] = 0;        while(qu.Count != 0)    {            KeyValuePair<int,                     int> p = (KeyValuePair<int,                                            int>)qu.Peek();                                                    // Dequeue a vertex from queue        qu.Dequeue();        vis[p.Key] =true;                // Get all adjacent vertices of the dequeued        // vertex s. If any adjacent has not        // been visited then enqueue it        foreach(intchildintree[p.Key])        {            if(!vis[child])            {                qu.Enqueue(newKeyValuePair<int,int>(                           child, p.Key));                level[child] = level[p.Key] + 1;                maxLevel = Math.Max(maxLevel, level[child]);                nodes[level[child]].Add(child);            }        }    }} // Function to display// the patternstaticvoiddisplay(){        for(inti = maxLevel; i >= 0; i--)    {        intlen = nodes[i].Count;                // Printing all nodes        // at given level        for(intj = 0; j < len / 2; j++)        {            Console.Write((int
                            
                         |