Answer the question
In order to leave comments, you need to log in
How to implement binary tree width padding in PHP?
Good afternoon, there is such a task
given a set of numbers, make a binary tree (not DDP) from them, filling it in levels. This means that the first element is added to the first level, the second and third to the second level, the fourth to seventh elements to the third level, and so on.
How to solve this problem? Using a queue.
The first element of the set is placed at the root of the tree. We put this root in the queue twice. Now, for each next element of the set, we will create a new vertex, then remove one vertex from the queue, and if this vertex does not have a left child, then add the created vertex as a left child, if there is no right one, then as a right one. After that, the added vertex is added to the queue twice.
Each new vertex is added to the queue twice so that two children can be added to it: left and right.
class BinaryNode
{
public $value;
public $left = NULL;
public $right = NULL;
public function __construct ($value)
{
$this->value = $value;
}
}
// Рандомно заполним исходный массив
for ($i=0; $i<10; $i++)
{
$array[$i] = rand(0, 100);
}
// Корень
$node = new BinaryNode($array[0]);
// Создадим очередь и добавим 2 раза корень
$queue = new SplQueue();
$queue->enqueue($node);
$queue->enqueue($node);
// В цикле перебираем массив и выполняем действия согласно алгоритму
for ($i=1; $i<count($array); $i++)
{
$t = $queue->dequeue();
$node = new BinaryNode($array[$i]);
if($t->left == null)
$t->left = $node;
else
$t->right = $node;
$queue->enqueue($node);
$queue->enqueue($node);
}
Answer the question
In order to leave comments, you need to log in
// Root
$node = new BinaryNode($array[0]);
$root = $node // store the root node in $root
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question