簡體   English   中英

在php中獲取二叉樹中的最后一個左孩子

[英]Get last Left Child in binary tree in php

我試圖在二叉樹中獲取贊助商 ID 的最后一個左孩子。 像:這是目前的情況(如圖),當id7在他的左側添加一個客戶(其id為14)時,它將在id10(已知的id14的上線)下加入。 因為它是 id7 的最后一個左孩子。

我嘗試了很多示例,例如: PHP 計算二叉樹中的下線數量

,但沒覺得有用在此處輸入圖片說明

那么,我如何找到贊助商 id 7. 的最后一個左節點,它在插入新客戶時使用。

這是我的數據庫:---“cm-customers”

在此處輸入圖片說明

任何幫助將不勝感激。 提前致謝。

在 MySQL 8.0 中,您可以使用遞歸查詢執行此操作:

with recursive nodes as (
    select serial_id, upline, left pos, 1 lvl from customers where upline = 0
    union all
    select c.serial_id, c.upline, n.left + c.left, n.lvl + 1
    from nodes n
    inner join customers c on c.upline = n.serial_id
)
select *
from nodes
order by lvl desc, pos desc
limit 1

查詢從根到葉遍歷層次樹,同時跟蹤每個節點的級別以及訪問了多少“左”節點。 然后,您可以使用此信息來識別最深、最左側的節點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM