При заданном двоичном дереве обход уровня порядка печати выполняется так, что узлы всех уровней печатаются в отдельных строках.
Например, рассмотрим следующее дерево
Example 1:
Output for above tree should be
20
8 22
4 12
10 14
Example 2:
1
/ \
2 3
/ \ \
4 5 6
/ \ /
7 8 9
Output for above tree should be
1
2 3
4 5 6
7 8 9<
Обратите внимание, что это отличается от простого обхода порядка уровней, когда нам нужно печатать все узлы вместе. Здесь нам нужно напечатать узлы разных уровней в разных строках.
Простое решение состоит в том, чтобы напечатать, используя рекурсивную функцию, обсужденную в посте прохождения порядка уровней, и печатать новую строку после каждого вызова printGivenLevel () .
C ++
void printLevelOrder( struct node* root)
{
int h = height(root);
int i;
for (i=1; i<=h; i++)
{
printGivenLevel(root, i);
printf ( "\n" );
}
}
void printGivenLevel( struct node* root, int level)
{
if (root == NULL)
return ;
if (level == 1)
printf ( "%d " , root->data);
else if (level > 1)
{
printGivenLevel(root->left, level-1);
printGivenLevel(root->right, level-1);
}
}
|
Джава
static void printLevelOrder(Node root)
{
int h = height(root);
int i;
for (i= 1 ; i<=h; i++)
{
printGivenLevel(root, i);
System.out.println();
}
}
void printGivenLevel(Node root, int level)
{
if (root == null )
return ;
if (level == 1 )
System.out.println(root.data);
else if (level > 1 )
{
printGivenLevel(root.left, level- 1 );
printGivenLevel(root.right, level- 1 );
}
}
|
python3
def printlevelorder(root):
h = height(root)
for i in range ( 1 , h + 1 ):
givenspirallevel(root, i)
def printGivenLevel(root, level):
if root is None :
return root
if level = = 1 :
print (root.val, end = ' ' )
elif level > 1 :
printGivenLevel(root.left, level - 1 )
printGivenLevel(root.right, level - 1 )
|
C #
static void printGivenLevel(Node root, int level)
{
if (root == null )
return ;
if (level == 1)
Console.WriteLine(root.data);
else if (level > 1)
{
printGivenLevel(root.left, level-1);
printGivenLevel(root.right, level-1);
}
}
|
Временная сложность вышеуказанного решения составляет O (n 2 )
Как изменить итеративный обход порядка уровней (метод 2 этого ) для уровней строка за строкой?
Идея похожа на этот пост. Мы считаем узлы на текущем уровне. И для каждого узла мы ставим его потомков в очередь.
C ++
#include <iostream> #include <queue>
using namespace std;
struct node
{
struct node *left;
int data;
struct node *right;
};
void printLevelOrder(node *root)
{
if (root == NULL) return ;
queue<node *> q;
q.push(root);
while (q.empty() == false )
{
int nodeCount = q.size();
while (nodeCount > 0)
{
node *node = q.front();
cout << node->data << " " ;
q.pop();
if (node->left != NULL)
q.push(node->left);
if (node->right != NULL)
q.push(node->right);
nodeCount--;
}
cout << endl;
}
}
node* newNode( int data)
{
node *temp = new node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
int main()
{
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);
printLevelOrder(root);
return 0;
}
|
Джава
import java.util.LinkedList;
import java.util.Queue;
public class LevelOrder
{
static class Node
{
int data;
Node left;
Node right;
Node( int data){
this .data = data;
left = null ;
right = null ;
}
}
static void printLevelOrder(Node root)
{
if (root == null )
return ;
Queue<Node> q = new LinkedList<Node>();
q.add(root);
while ( true )
{
int nodeCount = q.size();
if (nodeCount == 0 )
break ;
while (nodeCount > 0 )
{
Node node = q.peek();
System.out.print(node.data + " " );
q.remove();
if (node.left != null )
q.add(node.left);
if (node.right != null )
q.add(node.right);
nodeCount--;
}
System.out.println();
}
}
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 );
printLevelOrder(root);
}
}
|
python3
class newNode:
def __init__( self , data):
self .val = data
self .left = None
self .right = None
def printLevelOrder(root):
if root is None :
return
q = []
q.append(root)
while q:
count = len (q)
while count > 0 :
temp = q.pop( 0 )
print (temp.val, end = ' ' )
if temp.left:
q.append(temp.left)
if temp.right:
q.append(temp.right)
count - = 1
print ( ' ' )
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 );
printLevelOrder(root);
|
C #
using System;
using System.Collections.Generic;
public class LevelOrder
{
class Node
{
public int data;
public Node left;
public Node right;
public Node( int data)
{
this .data = data;
left = null ;
right = null ;
}
}
static void printLevelOrder(Node root)
{
if (root == null )
return ;
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
while ( true )
{
int nodeCount = q.Count;
if (nodeCount == 0)
break ;
while (nodeCount > 0)
{
Node node = q.Peek();
Console.Write(node.data + " " );
q.Dequeue();
if (node.left != null )
q.Enqueue(node.left);
if (node.right != null )
q.Enqueue(node.right);
nodeCount--;
}
Console.WriteLine();
}
}
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);
printLevelOrder(root);
}
}
|
Выход:
1
2 3
4 5 6
Временная сложность этого метода составляет O (n), где n — количество узлов в данном двоичном дереве.
Уровень прохождения заказа строка за строкой | Набор 2 (с использованием двух очередей)
Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по обсуждаемой теме
Рекомендуемые посты:
Печатать уровень обхода заказа построчно | Комплект 1
0.00 (0%) 0 votes