dongpian6319 2013-07-24 10:23
浏览 55
已采纳

遍历二叉树的递归函数

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.

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);
  • 写回答

2条回答 默认 最新

  • doumiang0597 2013-07-24 11:47
    关注

    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);)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?