VB.Net数据结构系列 第4章 树 4.3.2 二叉树的广度优先遍历

Code4-2

Node.vb

Public Class Node
    Private pdata As Object

    Private pright As Node

    Public ReadOnly Property [data] As Object
        Get
            Return pdata
        End Get
    End Property

    Public Property left As Node
    Public Property right As Node

    Public Sub New(ByVal data As Object)
        Me.pdata = data
    End Sub

    Public Function ToString() As String
        Return pdata.ToString
    End Function
End Class

BinaryTree.vb

Imports System.Collections

Public Class BinaryTree
    Private phead As Node
    Private Chars() As Char

    Public ReadOnly Property head As Node
        Get
            Return phead
        End Get
    End Property

    Public Sub New(ByVal constructStr As String)
        Chars = constructStr.ToCharArray
        phead = New Node(Chars(0))
        Add(phead, 0)
    End Sub

    '增加各个结点的值
    Private Sub Add(ByVal parent As Node, ByVal index As Integer)
        Dim leftindex As Integer = index * 2 + 1
        If leftindex < Chars.Length Then
            If Chars(leftindex) <> "#" Then
                parent.left = New Node(Chars(leftindex))
                Add(parent.left, leftindex)
            End If
        End If

        Dim rightindex As Integer = index * 2 + 2
        If rightindex < Chars.Length Then
            If Chars(rightindex) <> "#" Then
                parent.right = New Node(Chars(rightindex))
                Add(parent.right, rightindex)
            End If
        End If
    End Sub

    '调用递归广度遍历
    Public Sub LevelOrder()
        Dim queue As New Queue
        queue.Enqueue(head)
        Do While queue.Count > 0
            Dim node As Node = CType(queue.Dequeue, Node)
            Console.Write(node.ToString)
            If IsNothing(node.left) = False Then
                queue.Enqueue(node.left)
            End If
            If IsNothing(node.right) = False Then
                queue.Enqueue(node.right)
            End If
        Loop
    End Sub

End Class

Module1.vb

Module Module1

    Sub Main()
        Dim bTree As New BinaryTree("ABCDE#F")
        bTree.LevelOrder()
        Console.ReadKey()
    End Sub

End Module

 

你可能感兴趣的:(数据结构)