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