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

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?