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 Then		'Store data in left branch if NewData < NodeData		If LeftBranch Is Nothing Then			Set LeftBranch = New CBinarySearchTree		End If		LeftBranch.AddNode NewData	Else		'Store data in right branch if 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.

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist