在PHP中删除/折叠二叉树

时间:2013-07-21 17:29:44

标签: php tree binary-tree collapse

我有一张这样的表

----------------------------------
CUSTOMER_ID    | REF_CUSTOMER_ID |   
----------------------------------
1              | NULL            | 
2              | 1               | 
3              | 2               | 
4              | 2               | 
5              | 3               |
6              | 3               | 
7              | 4               |
8              | 4               |  
9              | 1               |  
----------------------------------

从该表中可以知道2是1的孩子,3,4是2的孩子等。  这使树看起来像这样

                1
                |
        ------------------
        |                |
        2                9
        |                |
    -----------     
    |        |                
    3        4   
    |        |
  -----    -----
  |   |    |   |
  5   6    7   8 
好吧,在每个父母有2个孩子和4片叶子之后,在这种情况下2有3和4的孩子和5,6,7,8的叶子,树将不得不崩溃。这意味着它只会在树中留下1。但是因为2是1的孩子,3,4是叶1,1还没有完成它的循环,所以1还没有崩溃。

问题

我如何仍然以root身份折叠2树,但保留其子树和叶子的树?我该如何处理?我必须创建另一个表吗?或者只使用现有的表格?

1 个答案:

答案 0 :(得分:0)

您不必使用其他表,可以使用递归删除树:

伪代码:

function deleteChildBranches(node)
{
    get left and right child nodes
    if(there's left branch node)
       deleteANode(left branch node)
    if(there's right branch node)
       deleteANode(right branch node)       
}

function deleteANode(node)
{
    get left and right child nodes
    if(there's left branch node)
       deleteANode(left branch node)
    if(there's right branch node)
       deleteANode(right branch node)
    delete this node
} 

此代码首先遍历树到底部,节点从底部到顶部删除。

相关问题