【问题标题】:calculate left and right children count in binary tree in sql server 2008 r2在 sql server 2008 r2 中计算二叉树中的左右子节点数
【发布时间】:2011-10-18 14:12:06
【问题描述】:

我在 sql server 2008 r2 中实现了一个二叉树,格式如下

表二进制信息

父ID----LeftChildID----RightChildID

1--------------2--------------3

2--------------4----------------5

3--------------6----------------7

      1(Root)    
  2   |    3     
4   5 |  6   7

等等。现在我必须计算成员左右两侧的总成员数,比如 1 有 3 个左孩子和 3 个右孩子。 2 有 1 个左孩子和 1 个右孩子。

我可能在 c# 中可以做到这一点,但有没有办法在 sql server 中使用 Procs 或 Functions 做到这一点?

我无法使用 heirarchyid,因为该表中已经填充了数据。

P.S需要单独计算,即总左孩子和总右孩子。

【问题讨论】:

    标签: sql-server binary-tree


    【解决方案1】:

    你可以像这样创建一个递归过程:

    CREATE PROCEDURE BinaryTreeCount
        @ParentId int,
        @HowMany int OUTPUT
    as
    BEGIN
        DECLARE @childenCount int
        SET @childenCount = 0
        SET @HowMany = 0
    
        SET @LeftChildId = null
        SET @RightChildId = null
    
        SELECT @LeftChildId = LeftChildID
             , @RightChildId = RightChildID
          FROM yourTableName
         WHERE ParendId = @ParentId
    
        if (@LeftChildId is not null) begin
            @howMany = @howMany + 1
            exec BinaryTreeCount @ParentId = @LeftChildId
                               , @HowMany  = @childenCount OUTPUT
            @howMany = @howMany + @childenCount
        end 
    
        if (@RightChildId is not null) begin
            @howMany = @howMany + 1
            exec BinaryTreeCount @ParentId = @RightChildId
                               , @HowMany  = @childenCount OUTPUT
            @howMany = @howMany + @childenCount
        end 
    END
    

    这只是一个想法,我没有测试过。

    【讨论】:

    • 非常感谢...上面的过程返回孩子的总累积总和,我需要分别左右总计数。我想这样做会使 proc 更难理解并且更容易出错。我总是可以分别为直接的左右孩子运行这个 proc 以获得正确的总计数并将它们 +1...再次感谢
    【解决方案2】:

    由于您使用的是 SQL 2008,我相当确定您可以使用递归 CTE(公用表表达式)来做到这一点:http://msdn.microsoft.com/en-us/library/ms186243.aspx

    如果我面前没有 SQL 副本,恐怕我很难显示代码。

    【讨论】:

      猜你喜欢
      • 2023-03-25
      • 2020-12-17
      • 1970-01-01
      • 2015-08-31
      • 1970-01-01
      • 1970-01-01
      • 2019-05-05
      • 2012-03-02
      • 1970-01-01
      相关资源
      最近更新 更多