Querying taxonomy terms with the level hierarchy
have you reviewed taxonomy_get_tree() documentation? http://api.drupal.org/api/drupal/modules--taxonomy--taxonomy.module/function/taxonomy_get_tree/6 I guess that taxonomy_get_tree() documentation and code function could be a guidance.


  taxonomy_get_tree
  ...
  
  Return value
  
  An array of all term objects in the tree. Each term object is extended
  to have "depth" and "parents" attributes in addition to its normal
  ones.