Recursive Function to Traverse Binary Tree

I have mySQL table like:

userid left_refid right_ref_id
1             3        4
3             5        6

and so on. I want to go through the binary tree and display all userid, and left and right ref ids.

Read More

This is the code I used, but it prints 134 continuously.

function display_childs($parent) {

    //$result = mysql_query("SELECT title FROM tree WHERE parent=".$parent.'";'); 
    global $wpdb;
    $prefix=$wpdb->prefix;
    if($parent==0){
        $parent=3;
    }
    $user_ref_1 = $wpdb->get_results( $wpdb->prepare("SELECT * FROM wp_user_reference WHERE user_id=".$parent."" ));

    foreach($user_ref_1 as $urd)
    {
        echo $urd->user_id;
        echo $urd->left_zone_id;
        echo $urd->right_zone_id;
        echo '<br>'; 
        $user_idpass=$urd->user_id;
    }

    display_childs($user_idpass); 
    unset($user_idpass);
    unset($parent);
}

display_childs(0);

Related posts

Leave a Reply

2 comments

  1. Normally this tree doesn’t support recursion but you can try the between operator in the where clause: select * from where left_ref_id between 3, 7 and right_ref_id between 3,7 to pull the children. Look for a nested set table or a celko tree.

    Update: You can also try to recursively call ‘display_childs($urd->left_zone_id)anddisplay_childs($ur->right_zone_id)` in the for-loop.

  2. Your current function recursively calls itself display_childs($user_idpass);, however this will always be called with the ‘parent’ id and never the ‘child’ ids

    Within the foreach loop you should also be calling display_childs($urd->left_zone_id) and display_childs($urd->right_zone_id) (and remove the call to display_childs($user_idpass);)