-1

我有一张这样的桌子

----------------------------------
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 还不能折叠。

问题

我如何仍然将 2 的树折叠为根,但保持 1 的树及其子节点和叶子?我该如何处理?我必须创建另一个表吗?或者只是使用现有的表?

4

1 回答 1

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
} 

这段代码会先遍历一棵树到底部,从底部到顶部删除节点。

于 2013-07-21T17:35:16.090 回答