1.把二元查找树转变成排序的双向链表

1.把二元查找树转变成排序的双向链表
 题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
   
  10
  / /
 6 14
 / / / /
4 8 12 16
   
 转换成双向链表
4=6=8=10=12=14=16。
   
 首先我们定义的二元查找树 节点的数据结构如下:
 struct BSTreeNode
{
  int m_nValue; // value of node
  BSTreeNode *m_pLeft; // left child of node
  BSTreeNode *m_pRight; // right child of node
};

 

VB.NET codes as below:

 

Module Module1

 

    Sub Main()

        Dim n1 = New Node(Of Integer)() With {.TheValue = 4}

        Dim n2 = New Node(Of Integer)() With {.TheValue = 5}

        Dim n3 = New Node(Of Integer)() With {.TheValue = 6}

        Dim n4 = New Node(Of Integer)() With {.TheValue = 7}

        Dim n5 = New Node(Of Integer)() With {.TheValue = 2, .Left = n1, .Right = n2}

        Dim n6 = New Node(Of Integer)() With {.TheValue = 3, .Left = n3, .Right = n4}

        Dim n7 = New Node(Of Integer)() With {.TheValue = 1, .Left = n5, .Right = n6}

 

        Dim tree = New Tree(Of Integer)() With {.Root = n7}

        Dim link = Fun(tree)

 

        Dim n = link.Start

 

        While Not n Is Nothing

            Console.Write("{0}   ", n.TheValue)

            n = n.Right

            If Not n Is Nothing Then

                Console.WriteLine(n.Left.TheValue)

            End If

        End While

 

        Console.ReadKey()

    End Sub

 

    Public Function Fun(Of T)(ByVal theTree As Tree(Of T)) As Link(Of T)

        Dim start = Fun(Of T)(theTree.Root)

 

        While Not start.Left Is Nothing

            start = start.Left

        End While

 

        Return New Link(Of T)() With {.Start = start}

    End Function

 

    Private Function Fun(Of T)(ByVal root As Node(Of T)) As Node(Of T)

 

        If Not root.Left Is Nothing Then

            Fun(Of T)(root.Left)

 

            While Not (root.Left.Right Is Nothing)

                root.Left = root.Left.Right

            End While

 

            root.Left.Right = root

        End If

 

        If Not root.Right Is Nothing Then

            Fun(Of T)(root.Right)

 

            While Not (root.Right.Left Is Nothing)

                root.Right = root.Right.Left

            End While

 

            root.Right.Left = root

        End If

 

        Return root

    End Function

 

    Class Node(Of T)

        Public Property TheValue As T

 

        Public Property Left As Node(Of T)

        Public Property Right As Node(Of T)

    End Class

 

    Class Link(Of T)

        Public Property Start As Node(Of T)

    End Class

 

    Class Tree(Of T)

        Public Property Root As Node(Of T)

    End Class

End Module

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值