Open kimpro82 opened 10 months ago
Add Tree
class to manage the tree structure
' Define a class to manage the tree structure.
Class Tree
Public Root As TreeNode
' Method to insert a node with a specific value as a child of a parent node.
Public Sub Insert(parentValue As Variant, newValue As Variant)
Dim newNode As New TreeNode
newNode.Value = newValue
If Root Is Nothing Then
' The tree is empty. Create the root node.
Set Root = newNode
Else
' Search for the parent node.
Dim parentNode As TreeNode
Set parentNode = SearchNode(Root, parentValue)
If Not parentNode Is Nothing Then
' Add the new node as a child of the parent node.
parentNode.Children.Add newNode
Else
' Parent node not found.
Debug.Print "Parent node with value " & parentValue & " not found."
End If
End If
End Sub
' Method to search for a node with a specific value.
Private Function SearchNode(startNode As TreeNode, searchValue As Variant) As TreeNode
Dim currentNode As TreeNode
If startNode.Value = searchValue Then
' Node found.
Set SearchNode = startNode
Exit Function
Else
' Recursively search among the children.
For Each currentNode In startNode.Children
Set SearchNode = SearchNode(currentNode, searchValue)
If Not SearchNode Is Nothing Then Exit Function
Next currentNode
End If
' Node not found.
Set SearchNode = Nothing
End Function
' Method to display the tree structure.
Public Sub Display()
DisplayNode Root, 0
End Sub
' Recursive method to display a node and its children.
Private Sub DisplayNode(node As TreeNode, level As Integer)
Dim i As Integer
For i = 1 To level
Debug.Print " ";
Next i
Debug.Print node.Value
For Each childNode In node.Children
DisplayNode childNode, level + 1
Next childNode
End Sub
End Class
Test
Sub TestTreeOperations()
' Create a tree and insert nodes.
Dim myTree As New Tree
myTree.Insert "Root", "Child1"
myTree.Insert "Root", "Child2"
myTree.Insert "Child1", "Grandchild1"
myTree.Insert "Child1", "Grandchild2"
myTree.Insert "Child2", "Grandchild3"
' Display the initial tree structure.
Debug.Print "Initial Tree Structure:"
myTree.Display
Debug.Print "------------------------"
' Traverse the tree (Depth-First Search).
Debug.Print "Depth-First Search:"
TraverseDF myTree.Root
Debug.Print "------------------------"
' Delete a node.
myTree.Delete "Child1"
' Display the updated tree structure.
Debug.Print "Tree Structure after Deleting 'Child1':"
myTree.Display
Debug.Print "------------------------"
End Sub
' Method to traverse the tree using Depth-First Search.
Sub TraverseDF(startNode As TreeNode)
Debug.Print startNode.Value
Dim childNode As Variant
For Each childNode In startNode.Children
TraverseDF childNode
Next childNode
End Sub
By ChatGPT
Define
TreeNode
Class