| |
8.32.1.Define your own binary tree |
|
Public Class TreeNode
Private mLeftNode As TreeNode
Private mData As Integer
Private mRightNode As TreeNode
Public Sub New(ByVal nodeData As Integer)
mData = nodeData
mRightNode = Nothing
LeftNode = Nothing
End Sub ' New
Public Property LeftNode() As TreeNode
Get
Return mLeftNode
End Get
Set(ByVal value As TreeNode)
mLeftNode = value
End Set
End Property
Public Property Data() As Integer
Get
Return mData
End Get
Set(ByVal value As Integer)
mData = value
End Set
End Property ' Data
Public Property RightNode() As TreeNode
Get
Return mRightNode
End Get
Set(ByVal value As TreeNode)
mRightNode = value
End Set
End Property
Public Sub Insert(ByVal insertValue As Integer)
If insertValue < mData Then
If mLeftNode Is Nothing Then
LeftNode = New TreeNode(insertValue)
Else
LeftNode.Insert(insertValue)
End If
ElseIf insertValue > mData Then
If RightNode Is Nothing Then
RightNode = New TreeNode(insertValue)
Else
RightNode.Insert(insertValue)
End If
End If
End Sub
End Class
Public Class Tree
Private root As TreeNode
Public Sub New()
root = Nothing
End Sub ' New
Public Sub InsertNode(ByVal insertValue As Integer)
SyncLock (Me)
If root Is Nothing Then
root = New TreeNode(insertValue)
Else
root.Insert(insertValue)
End If
End SyncLock
End Sub
Public Sub PreorderTraversal()
SyncLock (Me)
DoTraversal(root)
End SyncLock
End Sub
Private Sub DoTraversal(ByVal node As TreeNode)
If node Is Nothing Then
Return
End If
Console.Write(node.Data & " ")
DoTraversal(node.LeftNode)
DoTraversal(node.RightNode)
End Sub
Public Sub InorderTraversal()
SyncLock (Me)
DoInorder(root)
End SyncLock
End Sub
Private Sub DoInorder(ByVal node As TreeNode)
If node Is Nothing Then
Return
End If
DoInorder(node.LeftNode)
Console.Write(node.Data & " ")
DoInorder(node.RightNode)
End Sub ' DoInorder
Public Sub PostorderTraversal()
SyncLock (Me)
DoPostorder(root)
End SyncLock
End Sub
Private Sub DoPostorder(ByVal node As TreeNode)
If node Is Nothing Then
Return
End If
DoPostorder(node.LeftNode)
DoPostorder(node.RightNode)
Console.Write(node.Data & " ")
End Sub
End Class
Module modTreeTest
Sub Main()
Dim tree As Tree = New Tree()
Dim insertValue As Integer
Dim i As Integer
Console.WriteLine("Inserting Values: ")
Dim randomNumber As Random = New Random()
For i = 1 To 10
insertValue = randomNumber.Next(100)
Console.Write(insertValue & " ")
tree.InsertNode(insertValue)
Next
Console.WriteLine("Preorder Traversal")
tree.PreorderTraversal()
Console.WriteLine("Inorder Traversal")
tree.InorderTraversal()
Console.WriteLine("Postorder Traversal")
tree.PostorderTraversal()
End Sub
End Module
|
|
Inserting Values:
17 20 77 11 86 68 51 23 62 80 Preorder Traversal
17 11 20 77 68 51 23 62 86 80 Inorder Traversal
11 17 20 23 51 62 68 77 80 86 Postorder Traversal
11 23 62 51 68 80 86 77 20 17 " |
8.32.Your Tree | | 8.32.1. | Define your own binary tree | | |
|