Skip to content

Binary Tree Function #589

Open
Open
@beshoo

Description

@beshoo

Allow me to provide guidance on how to efficiently create a binary tree using a function.

First and foremost, it is essential to establish a new column named "position." This will serve as a reference point for the placement of each node in the tree.

When adding a new node, it is essential to furnish its position and parent ID "p_id" to ensure that it is accurately placed within the tree.

Additionally, you have the option to include any pertinent information, such as the user's name, to add further context to the tree's structure.


public function insertNewNode($p_id, $position, $name): void
    {
        // Find the parent node
        $parent = tree::find($p_id);

        // Check if the parent has a child at the specified position
        $child = $parent->children()->where('position', $position)->first();
        if (!$child) {
            // The parent does not have a child at the specified position, so insert the new node at that position
            $newNode = tree::create(['name' => $name, 'position' => $position]);
            if ($position === 'left') {
                $parent->prependNode($newNode);
            } else {
                $parent->appendNode($newNode);
            }
        } else {
            // The parent has a child at the specified position, so find the next empty child at that position and append there
            $nextChild = $child;
            while ($nextChild->children()->where('position', $position)->exists()) {
                $nextChild = $nextChild->children()->where('position', $position)->first();
            }
            $newNode = tree::create(['name' => $name, 'position' => $position]);
            if ($position === 'left') {
                $nextChild->prependNode($newNode);
            } else {
                $nextChild->appendNode($newNode);
            }
        }
        // Call the addRewardPoints function to add reward points to the new node and its ancestors
        $this->addRewardPoints($newNode);
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions