Jump to content

Efficient Binary Tree


askbapi

Recommended Posts

I can create a Binary tree with help of PHP and MYSQL by create a recursive function. AND it work fine. BUT it is very slow. I create a tree with 9000+ nodes and it took 46 seconds only to create tree. Than I need to find the pairs on both side left and right.

 

So I was think it to create with array. How can i do it only with array.

 

MYSQL Table structure

 

>member_id

> parent_id

Link to comment
https://forums.phpfreaks.com/topic/193927-efficient-binary-tree/
Share on other sites

I doubt that implementation using arrays will be fast either.

 

You can also try to create a class like

 

class BinaryTreeNode {

  private $left;
  private $right;

  public function setLeft(BinaryTreeNode $node) {
    $this->left = $node;
  }

  public function setRight(BinaryTreeNode $node) {
    $this->right = $node;
  }

public function getLeft() {
    return $this->left;
  }

  public function setRight() {
    return $this->right;
  }

}

Thanks again for ur help.

 

Here is the a code that I created

while($gaRow = mysql_fetch_assoc($rResult))
{

$aMemCore[$i][1] = $gaRow['mem_idx'] ; // Member ID
            $aMemCore[$i][2] = $gaRow['mem_pntidx'] ; // Parent ID
$i++;
}

unset($gaRow);

function getNodes($preantid,$arr)
{
    for($j=0; $j <= 8473; $j++)
    {// echo $j;
        if($arr[$j][2]== $preantid)
        {
            echo "===<br>--".$arr[$j][1];
           getNodes($arr[$j][1],$arr);
                    
        }    
}
}

getNodes(0,$aMemCore);
unset($amemCore);

 

After this it brought the time from 42 to 22 secs. It ok but not gud.

 

Thanks again for ur help.

echo takes time. Try like this:

 

function getNodes($preantid,$arr)
{
    $result = '';
    for($j=0; $j <= 8473; $j++)
    {// echo $j;
        if($arr[$j][2]== $preantid)
        {
            $result .= "===<br>--".$arr[$j][1];
           $result .= getNodes($arr[$j][1],$arr);
                   
        }   
   }
  return $result;
}

echo getNodes(0,$aMemCore);
unset($amemCore);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.