Create binary trees in PHP

1

Someone knows how to make a binary tree in php, which allows to insert and delete nodes, I am new in this of the programming, if someone could show me an example I would appreciate it.

    
asked by Francisco Cortez 24.03.2018 в 19:01
source

1 answer

0

I will try to give you a simple example:

public class Node {

    private $leftNode;
    private $rightNode;

    public function setLeftNode($node){
       $this->leftNode = $node;
    }
    public function setRightNode($node){
       $this->rightNode = $node;
    }
    public function getLeftNode(){
       return $this->leftNode;
    }
    public function getRightNode(){
       return $this->rightNode;
    }
    public function isLeaf(){
        return $this->leftNode === null && $this->rightNode === null;
    }
}

From this structure you can start playing by adding nodes and removing, for example:

$nodo = new Nodo();
$nodo->setRightNode(new Node());

You have created a node that has a right child, and so you can build what you need. To eliminate, simply call the set sending it null as a parameter.

It has only right and left children because it is a binary tree, otherwise it would be a collection of children.

Greetings

    
answered by 26.03.2018 / 16:07
source