Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Visual Basic
Expertise: Intermediate
Sep 10, 1998



Full Text Search: The Key to Better Natural Language Queries for NoSQL in Node.js

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 CBinarySearchTree
Private RightBranch As CBinarySearchTree
Private NodeData As String
'Adds a new value to the binary tree
Public 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
		'Store data in right branch if NewData 
		'>= NodeData
		If RightBranch Is Nothing Then
			Set RightBranch = New CBinarySearchTree
		End If
		RightBranch.AddNode NewData
	End If
End Sub

'Displays all values in this tree
'If called on a child node, displays all 
'values in this branch
Public Sub TraverseTree()
	'Traverse left branch
	If Not LeftBranch Is Nothing Then
	End If
	'Display this node
	MsgBox NodeData
	'Traverse right branch
	If Not RightBranch Is Nothing Then
	End If
End 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.

David Doknjas
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date