Jump to content

Counting binary tree


Nuv

Recommended Posts

I am trying to count left node of a binary tree.I made a function but my result is always 3 .

 

Code:-

 

<?php
  include'config.php';  // Connect database

  function leftcount($node)   //Function to calculate leftcount
  {
    $sql = "SELECT lchild,rchild FROM tree WHERE parent = '$node'";
    $execsql = mysql_query($sql);
    $array = mysql_fetch_array($execsql);
    
    if(!empty($array['lchild']))
    {
      $count++;
      leftcount($array['lchild']);  
    } 
    if(!empty($array['rchild']))
    {
       $count++;
       leftcount($array['rchild']); 
    }
    
    $totalcount = 1 + $count;
    return $totalcount;
    
  }
  
  $parent = "2";
  $left = leftcount($parent);
  echo $left;
  
?>

 

Can someone please point the error in my logic ? I searched google but i only got scripts with classes and i don't want to use classes.

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

You're returning the totalcount from the function, but not doing anything with it when you call the function recursively. Try something like:

<?php
  include 'config.php';  // Connect database

  function leftcount($node)   //Function to calculate leftcount
  {
    $sql = "SELECT lchild,rchild FROM tree WHERE parent = '$node'";
    $execsql = mysql_query($sql);
    $array = mysql_fetch_array($execsql);
    
    if(!empty($array['lchild']))
    {
      $count += leftcount($array['lchild']);  
    } 
    if(!empty($array['rchild']))
    {
       $count += leftcount($array['rchild']); 
    }
    
    $totalcount = 1 + $count;
    return $totalcount;
    
  }
  
  $parent = "2";
  $left = leftcount($parent);
  echo $left;
  
?>

 

Ken

 

You're returning the totalcount from the function, but not doing anything with it when you call the function recursively. Try something like:

<?php
  include 'config.php';  // Connect database

  function leftcount($node)   //Function to calculate leftcount
  {
    $sql = "SELECT lchild,rchild FROM tree WHERE parent = '$node'";
    $execsql = mysql_query($sql);
    $array = mysql_fetch_array($execsql);
    
    if(!empty($array['lchild']))
    {
      $count += leftcount($array['lchild']);  
    } 
    if(!empty($array['rchild']))
    {
       $count += leftcount($array['rchild']); 
    }
    
    $totalcount = 1 + $count;
    return $totalcount;
    
  }
  
  $parent = "2";
  $left = leftcount($parent);
  echo $left;
  
?>

 

Ken

 

 

Ah how can i miss that :(

Thankyou though. It worked.

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.