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

报告相同问题?

悬赏问题

  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元