2017年5月21日 星期日

vb版 BST建立及巡訪

一個TextBox1輸入5~30個皆不相同的整數以「,」隔開
一個Label1顯示輸出
一個按鈕,執行(1)建二元搜尋樹,(2)在Label1顯示{前序、中序、後序}巡訪結果
程式碼如下:
Public Class Form1
    Class BT
        Public data As Integer
        Public lch As BT
        Public rch As BT
        Sub New()
            lch = Nothing
            rch = Nothing
        End Sub
    End Class
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim dat() = TextBox1.Text.Split(",")    '依 , 分割為 陣列
        Dim rt As BT = Nothing  '一開始 樹根為 nothing
        For i = 0 To UBound(dat)
            Dim k As Integer = dat(i)
            add(k, rt)                             '新增 1 node
        Next
        Dim s As String = "" : pre(s, rt)   '前序
        Label1.Text = "前序:" & s

        s = "" : ino(s, rt)   '中序
        Label1.Text &= vbNewLine
        Label1.Text &= "中序:" & s

        s = "" : pos(s, rt)   '後序
        Label1.Text &= vbNewLine
        Label1.Text &= "後序:" & s
    End Sub

    '將資料 k 新增至 樹根為 root 的 bst 樹中
    Sub add(ByVal k As Integer, ByRef root As bt)
        Dim node As New BT
        node.data = k
        If root Is Nothing Then
            root = node
            Return
        End If
        If k < root.data Then
            add(k, root.lch)
        Else
            add(k, root.rch)
        End If
    End Sub

    ' 前序巡訪
    Sub pre(ByRef s As String, ByVal node As bt)
        If node Is Nothing Then Return
        If s <> "" Then s &= ","
        s &= node.data
        pre(s, node.lch)
        pre(s, node.rch)
    End Sub
 
 ' 中序巡訪
    Sub ino(ByRef s As String, ByVal node As bt)
        If node Is Nothing Then Return
        ino(s, node.lch)
        If s <> "" Then s &= ","
        s &= node.data
        ino(s, node.rch)
    End Sub
 
  ' 後序巡訪
    Sub pos(ByRef s As String, ByVal node As bt)
        If node Is Nothing Then Return
        pos(s, node.lch)
        pos(s, node.rch)
        If s <> "" Then s &= ","
        s &= node.data
    End Sub

End Class

0 意見:

張貼留言