Instead of implementing your own class, using the TreeNode class, which is designed for this, makes your code much easier to understand, and has the added advantage of being native to the TreeView, which means all we have to do is add the base node and call ExpandAll and we have a graphical representation of our tree. Also what you want to do is well suited to a recursive routine. Here's a way that will build the tree structure. Whenever the child nodes are being added it skips any with a value already above it in the tree.
Private Sub btnAnswers_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
'Declare initial treenode with the value we want.
Dim Tree As New TreeNode("5")
'Declare the string of bits.
Dim input As String = "1001001001"
'Start the recursive routine
CalculateTreeNodes(Tree, input)
'Show the tree
TreeView1.Nodes.Add(Tree)
TreeView1.ExpandAll()h
End Sub
Private Sub CalculateTreeNodes(CurrentNode As TreeNode, directions As String)
If directions = "" Then Return
'Parse the text of the current node as byte
Dim value As Byte = Byte.Parse(CurrentNode.Text)
'Get the direction we want and truncate the string
Dim direction As Directions = CType([Enum].Parse(GetType(Directions), directions(0).ToString), Directions)
If directions.Length > 0 Then
directions = directions.Substring(1)
End If
'Get a list of the values of all the parent nodes above this one.
Dim Values As New List(Of Byte)
GetPrevValues(CurrentNode, Values)
'build our child nodes based on the direction we want.
Select Case direction
Case WindowsApplication7.Directions.Higher
For i As Byte = value + 1 To 10
If Not Values.Contains(i) Then
Dim node As New TreeNode(i.ToString)
CurrentNode.Nodes.Add(node)
'Calculate the children for each node
CalculateTreeNodes(node, directions)
End If
Next
Case WindowsApplication7.Directions.Lower
For i As Byte = 1 To value - 1
If Not Values.Contains(i) Then
Dim node As New TreeNode(i.ToString)
CurrentNode.Nodes.Add(node)
CalculateTreeNodes(node, directions)
End If
Next
End Select
End Sub
'recursive routine to find the parent values.
Private Sub GetPrevValues(CurrentNode As TreeNode, Values As List(Of Byte))
If Not CurrentNode Is Nothing Then
Values.Add(Byte.Parse(CurrentNode.Text))
GetPrevValues(CurrentNode.Parent, Values)
End If
End Sub
End Class
Public Enum Directions
Higher = 1
Lower = 0
End Enum
To find the longest branches you could use a conditional to check if directions
is down to one character, then any children will be in the longest branches.