devxlogo

Implement a Binary Tree

Implement a Binary Tree

A binary search tree can be useful when you have to traverse a lot of data in sorted order. As this CBinarySearchTree class demonstrates, you can implement binary search trees easily using objects and recursion (both data recursion and procedural recursion):

 'class properties:Private LeftBranch As CBinarySearchTreePrivate RightBranch As CBinarySearchTreePrivate NodeData As String'Adds a new value to the binary treePublic Sub AddNode(NewData As String)	If Len(NodeData) = 0 Then		'Store data in current node if empty		NodeData = NewData	ElseIf NewData = NodeData		If RightBranch Is Nothing Then			Set RightBranch = New CBinarySearchTree		End If		RightBranch.AddNode NewData	End IfEnd Sub'Displays all values in this tree'If called on a child node, displays all 'values in this branchPublic Sub TraverseTree()	'Traverse left branch	If Not LeftBranch Is Nothing Then		LeftBranch.TraverseTree	End If	'Display this node	MsgBox NodeData	'Traverse right branch	If Not RightBranch Is Nothing Then		RightBranch.TraverseTree	End IfEnd Sub

Test this class by creating a new CBinarySearchTree object, calling AddNode a few times to store data, and then calling TraverseTree to see the results. Binary search trees don’t get much simpler than this.

devx-admin

Share the Post: