I'm storing a binary tree on a table in mysql database. The table have the columns id, parent, and others that isn't important. The columns is self explanatory.
I managed to get height of the tree:
$depth = 0;
/* @var $db PDO */
$stmt = $db->prepare( "SELECT id FROM wp_members WHERE parent = :parent AND matrix_id = :matrix_id" );
$q = new SplQueue();
$q->push( array( 0, 0 ) );
while (!$q->isEmpty()) {
$cur = $q->pop();
$stmt->bindParam( ':parent', $cur[0] );
$stmt->bindParam( ':matrix_id', $matrix_id );
$stmt->execute();
$ids = $stmt->fetchAll();
if ($cur[1] > $depth) $depth++;
if (count($ids) > 0) $q->add( 0, array( $ids[0]['id'], $cur[1] + 1));
if (count($ids) > 1) $q->add( 0, array( $ids[1]['id'], $cur[1] + 1));
}
return $depth;
PS: matrix_id => let's call tree id
It returns the height of the tree correct, but the problem is that database has more than 18k of nodes, and this takes a lot of time just to get tree height.
What I want to know is what I can do do solve this situation ? it takes more than 60secs to get height of the tree.