Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Binary Tree Function #589

Open
beshoo opened this issue Sep 9, 2023 · 0 comments
Open

Binary Tree Function #589

beshoo opened this issue Sep 9, 2023 · 0 comments

Comments

@beshoo
Copy link

beshoo commented Sep 9, 2023

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);
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant