Create generic tree : Generic Tree « Generics « VB.Net Tutorial






Imports System.Collections.Generic
Imports System.ComponentModel
public class Test
   public Shared Sub Main
        Dim family_tree As New Tree(Of MyNode)
        Dim root As TreeNode(Of MyNode) = family_tree.MakeRoot(New MyNode("Me"))

        Dim child1 As TreeNode(Of MyNode) = root.AddChild(New MyNode("Child 1"))
        Dim child2 As TreeNode(Of MyNode) = root.AddChild(New MyNode("Child 2"))

        child1.AddChild(New MyNode("Grandchild 1"))
        child1.AddChild(New MyNode("Grandchild 2"))
        child2.AddChild(New MyNode("Grandchild 3"))
        child2.AddChild(New MyNode("Grandchild 4"))

        Console.WriteLine(family_tree.ToString())

   End Sub
End class


Public Class MyNode
    Public Name As String
    Public Sub New(ByVal new_name As String)
        Name = new_name
    End Sub
    Public Overrides Function ToString() As String
        Return Name
    End Function
End Class

Public Class Tree(Of data_type)
    Private m_Root As TreeNode(Of data_type) = Nothing
    Public Property Root() As TreeNode(Of data_type)
        Get
            Return m_Root
        End Get
        Set(ByVal value As TreeNode(Of data_type))
            m_Root = value
        End Set
    End Property

    Public Sub Clear()
        m_Root = Nothing
    End Sub

    Public Function MakeRoot(ByVal node_item As data_type) As TreeNode(Of data_type)
        m_Root = New TreeNode(Of data_type)(node_item)
        Return m_Root
    End Function

    Public Overrides Function ToString() As String
        Return m_Root.ToString()
    End Function
End Class

Public Class TreeNode(Of data_type)
    Public NodeObject As data_type
    Public Children As New List(Of TreeNode(Of data_type))

    Public Sub New(ByVal node_object As data_type)
        NodeObject = node_object
    End Sub

    Public Function AddChild(ByVal node_item As data_type) As TreeNode(Of data_type)
        Dim child_node As New TreeNode(Of data_type)(node_item)
        Children.Add(child_node)
        Return child_node
    End Function

    Public Shadows Function ToString(Optional ByVal indent As Integer = 0) As String
        Dim txt As String
        txt = New String(" "c, indent) & NodeObject.ToString & vbCrLf

        ' Add the children's text.
        For Each child As TreeNode(Of data_type) In Children
            txt &= child.ToString(indent + 2)
        Next child

        Return txt
    End Function
End Class
Me
  Child 1
    Grandchild 1
    Grandchild 2
  Child 2
    Grandchild 3
    Grandchild 4








9.6.Generic Tree
9.6.1.Create generic tree