用户操作
[留言]  [发消息]  [加为好友] 
订阅我的博客
XML聚合    FeedSky
订阅到鲜果
订阅到Google
订阅到抓虾
sky_blue的公告
文章分类
    存档

    原创  树的深度优先遍历 收藏

    下面是直接用深度优先搜索,优点是过程更自然,缺点是效率没有宽度优先搜索高  
       
      drop   proc   proc__tree  
      go  
       
      create   proc   proc__tree   (@parent   char(20))  
        as  
      begin  
          set   nocount   on  
          declare   @level   int   ,@i   int   ,@flag   int  
          declare   @stack   table   (parent   char(20),child   char(20),level   int,row   int   ,   flag   int)  
          select   @level   =   1,@i=1,@flag=1  
          insert   @stack   select   parent,child,   @level,0,1   from       new_tree     where   parent   =   @parent   and   child   is   not   null  
           
          while   @level   >   0  
          begin  
              if   exists   (select   *   from   @stack   where   level   =   @level   and   flag=1)  
              begin  
                    select   @parent   =   min(child)   from   @stack     where   level   =   @level   and   flag=1  
                    update   @stack   set   flag   =0   ,   row=@i   where   level   =   @level   and   child   =   @parent   and     flag   =1  
                    select   @i   =   @i   +1  
                    insert   @stack   select   parent,child,   @level   +   1,0,1   from       new_tree     where   parent   =   @parent   and   child   is   not   null  
                    if   @@rowcount   >   0  
                          select   @level   =   @level   +   1  
              end  
              else  
              begin  
                  select   @level   =   @level   -   1  
              end  
          end    
          select   row,parent   ,child,level   from   @stack   order   by   row  
          set   nocount   off  
      end  
      go  
      proc__tree   '1'  
     
     

    发表于 @ 2007年12月30日 20:11:00 | 评论( loading... ) | 编辑| 举报| 收藏

    旧一篇:树的宽度优先遍历

    • 发表评论
    • 评论内容:
    •  
    Copyright © sky_blue
    Powered by CSDN Blog