R
R
RiGs2014-11-27 13:54:56
PHP
RiGs, 2014-11-27 13:54:56

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.

Algorithm found
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.

I tried to write code, but I don’t understand how to get the result tree itself in the end?
Here is the BinaryNode class
class BinaryNode
{
    public $value;
    public $left  = NULL;
    public $right = NULL;
 
    public function __construct ($value)
    {
        $this->value = $value;
    }
}

and the implementation itself
// Рандомно заполним исходный массив
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);
}

What needs to be added, where to get the tree? I do not need to get a binary tree, I just need to fill in a structure such as a binary tree, and fill it exactly "in width". The structure looks like this. 2c7bd6457d5e4f21a7d3f835df11eaf1.pngThe elements must be added in the order shown in the picture.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
ldv, 2014-11-27
@Rigs

// Root
$node = new BinaryNode($array[0]);
$root = $node // store the root node in $root

A
Alexey, 2017-03-10
@masterfreelance

The error occurs because Category::findOne() returns null under certain conditions and, accordingly, the non object error

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question