Posts, page 2

Use the arrows beside each title, or press J and K, to move between posts.

3 min read

In this post I will look at the different types of agentic systems. AI is moving fast and it is easy to become confused with the constantly evolving technologies. Let's start!

There are two main types
1. Workflows
2. Agents

Workflows

A workflow is a series of steps that follow a predefined, rigid path. Predictability is high because you know exactly what the system will do, but this comes at the expense of flexibility. If one steps breaks then the whole process if likely to fail. There are five main types of workflow.

Prompt Chaining

This is probably one of the most common types of workflow out there. Given an input the LLM(Large Language Model) carries out a task and optionally hands the results to some code which will transform or clean the results before passing to another LLM, then these results can be passed to the next LLM in the chain and so on...

The key is that you are breaking down a complicated single task into smaller, manageable steps.

Routing

The routing workflow is where an initial router LLM analyzes and categorizes an incoming query and directs it to the most appropriate specialized sub-task.

Parallelization

The input is passed to a coordinator (code) that breaks the task into independent pieces. These run simultaneously across multiple LLMs. The last sub-task is not an LLM but some code that will take the results and aggregate them. This is best for speed and processing large volumes of data.

Orchestrator/worker

Here, an LLM acts as the manager. It dynamically decides which sub-tasks are needed and assigns them to "workers". The Orchestrator then synthesizes the various results into a final response. This is more flexible than standard parallelization because the "manager" adapts to the complexity of the query.

Evaluator

In this workflow you have two LLMs in a feedback loop. One is the generator and one in the evaluator. The first LLM takes the initial user prompt and creates a draft. The second one reviews the draft against a set of given criteria and provides detailed feedback. The generator receives the feedback and produces a second version. This continues until the evaluator produces a pass or has hit it's "max loops" limit. Without a "max loops" limit, an Evaluator and Generator can sometimes get stuck in an infinite loop (and burn your API budget!!).

Agents

Unlike workflows, Agents use a reasoning loop to determine their own path. They are characterized by their ability to use Tools—like searching the web or executing code to solve open-ended problems.

The LLM gets to choose it's own design and plot it's own path to choose how it will solve the problem. This power makes them very powerful but less predictable.

What are the drawbacks?

  1. Unpredictable path - you do not know which order the sub-tasks will be run but tools are used to give an agent boundaries
  2. What quality will the output be?
  3. Unpredictable costs, you don't know how long it will take to run

Mitigations

  1. Monitoring - it is essential have the visibility to understand what interactions are going on
  2. Guardrails - protection to ensure models are doing what they should be doing, safely, consistently and within the given boundaries

Conclusion

In the current landscape of AI engineering, Workflows remain the most popular choice for production-grade applications. This is because businesses value reliability and cost-control. Patterns like Prompt Chaining and Routing allow developers to build systems that are fast, explainable, and easy to debug. If you are building a customer support bot or an automated report generator, a structured workflow is usually your best bet.

However, the industry is rapidly shifting toward Agents and Evaluator-Optimizer loops for high-stakes or creative tasks. While more "expensive" in terms of compute and time, these systems provide a level of quality and autonomy that simple chains cannot match. They are becoming the standard for coding assistants, research tools, and complex problem-solving.

The Rule of Thumb

  • Use Workflows when the process is well-defined and you need 100% consistency.
  • Use Agents when the task is open-ended and the path to the solution is too complex to map out by hand.

Comments and sharing

2 min read

Sorry it has taken me so long to continue with this series. There were little things that got in the way such as C*****19, and going through redundancy but lets put those little things aside and recap. Last time we created a web service using node Express which will be used to capture environmental data from our Raspberry PI Sense Hat.

In this article we are going to hook things up by sending the data collected from the Raspberry PI, to our web service. We will also be updating our endpoints to handle the data correctly. Let's get started!

First of all open the collector.py file.

We are going to POST the data to our web service endpoint. Find the line where we are checking if we have reached the interval and replace it with the code shown here.

python
if minute_count == MEASUREMENT_INTERVAL:                                                                                 
    # Create the payload object                                                                                          
    payload = {                                                                                                              
      'date':dt.strftime("%Y/%m/%d %H:%M:%S"),                                                                             
      'temperature':round(temp_c,2),                                                                                       
      'pressure':round(sense.get_pressure(),2),                                                                            
      'humidity':round(sense.get_humidity(),2),                                                                        
    }                                                                                                                     
    data = urllib.urlencode(payload)                                                                                     
    request = urllib2.Request(END_POINT,data)                                                                            
    response = urllib2.urlopen(request).read()                                                                           
    print(payload)                                                                                           
    minute_count = 0;

We are using a couple of Python libraries called urllib and urllib2 to do the heavy lifting of encoding our payload and sending it across to our Node.js server.

All that is left is to add the new endpoint to our Node.js server to process the request and update the list to return an actual list of weather data. Exciting eh! Open up another terminal session and navigate to the server directory. Using your editor of choice open up the index.js file.

Update the endpoints as shown below.

python
// Provide service meta data
app.get('/api/environment/meta', (req,res) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.send({
        averageTemp:averageTemp,
        count:data.length,
        lastEntry:lastEntry
    } );
} );
// List all entries
app.get('/api/environment/entries', (req,res) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.send(data);
} );
app.post('/api/environment', (req,res) => {
    if (!isValid(req.body)) {
        res.status(400).send('Invalid request, required fields missing.');
        return;
    }
    const count = data.length + 1;
    const entry = {
        id:count,
        date:req.body.date,
        temperature:req.body.temperature,
        pressure:req.body.pressure,
        humidity:req.body.humidity
    }
    lastEntry = entry;
    total += parseFloat(req.body.temperature);
    averageTemp = total / count;
    data.push(entry);
    res.json(entry);
} );

You may recall last time we added a dummy /api/environment/entries endpoint which simply returned an empty array.

Let's flesh this out. The endpoint is defined as a POST method which means data is sent as part of the body of the request. We validate that we do indeed have a body then update the count metric. We then build a JSON object by pulling out the parts of the request we are interested in. Finally we update the lastEntry variable, work out the average temperature to date before updating our list.

With these changes in place we can run our collector and Node.js server to see the end to end implementation working in all its glory. I would recommend opening two separate terminals and laying them out side-by-side.

In the terminal for the Python collector start the data harvest using the command python collector.py. On your PI you should see regular temperature updates on the matrix display.

Raspberry PI Weather Station
Weather station running in the Raspberry PI

In the second terminal ensure you are in the collector/server directory and start the Node.js server using the command node index.js. If all is well you will see the message Listening on port 3000.

Terminal sessions running the collector and  Node.js server
Terminals sessions showing the collector and Node.js server running on the PI

After a while you will see entries printed in the server console indicating that the weather data has collected from the PI and sent it to our server.

Now comes the exciting bit. We can try out our new endpoints. Open a new browser tab and check the new endpoints are functioning correctly.

http://raspberrypi:3000/api/environment/entries

http://raspberrypi:3000/api/environment/meta

The new endpoints shown using the RESTED Chrome extension

Well there we have it. A simple way of using your PI to collect weather data. I hope this has been useful and inspired you to create your own projects using the PI!!

Comments and sharing

3 min read

Introduction

In the last article we created a Python script to collect environmental data from a Sense Hat equipped Raspberry PI.

This article will add to that by creating a web service that will display all logged entries. In the next blog post we will add the ability to upload data from PI to the web service.

This web service will be running on the Raspberry PI but of course it could run anywhere as long as it supplies an endpoint to enable consumers to use it.

Building a RESTful API - do's and do not's

The web service will use RESTful principles. REST is a set of best practises to use when designing an API. In a nutshell:

  • DO return JSON
  • DO set the Content-Type header correctly i.e. application/json. Note, when using the PATCH method the content type must be application/merge-patch+json
  • DON'T use verbs e.g. use /songs instead of listSongs/
  • DO use plurals e.g. /api/songs/2019
  • DO return error details in the response body
  • DO make use of status codes when returning errors
    • 400-bad request, 403-forbidden, 404-not found, 401-unauthorised, 500 server error
  • For CRUD operation return the following codes
MethodDescriptionURLResponse code
GETretrieve dataapi/customers200
POSTcreate dataapi/customers
{"name":"jon", "email":"a@a.com"}
201
PUTupdate dataapi/customers/1
{"name":"dave","email":"b@a.com"}
200
DELETEdelete dataapi/customers/1204
PATCHupdate partial dataapi/customers/1
{"op":"replace","path":"/email","value":"a@a.com"}]
204
REST method, actions and expected response codes.

Defining the endpoints

Our API will have three endpoints. This article is focussed on the first one, to list entries. The other two will be addressed in a later post.

/api/environment/entries - to list all entries

The resulting JSON will be something like this:

json
[
    {
        "id":1,
        "date":"2020/06/06 15:34:01",
        "temperature":"24.48",
        "pressure":"998.32",
        "humidity":"44.9"
    }
]

/api/environment/ - to create a new entry

/api/environment/meta - to retrieve metadata such as number of entries, average temperature and last entry that was uploaded

Creating the web service using Express

Let's get started! Connect your PI to the network either wirelessly or using a cable. I use an Ethernet cable directly plugged it into my laptop.

  1. Power up your PI!
  2. SSH into your PI. I used PuTTY
  3. Navigate to the collector directory we created the last blog post.
  4. mkdir server
  5. cd server

We are going to use Node.js to create our server. Node.js is based on the Chrome V8 Javascript engine but has added modules to deal with IO, HTTP and many more. It is basically a Javascript engine wrapped in a C++ exe. It has a single-threaded handler which hands off requests in an asynchronous manner so it is very suitable to quick high-throughput requests.

Out of the box it is very easy to create a simple REST API. We will be using another node module called express which makes managing routing much easier.

So first things first if you haven't already done so install node and npm on your PI. Here is a noice instructable showing how to do it.
https://www.instructables.com/id/Install-Nodejs-and-Npm-on-Raspberry-Pi/

When you have successfully installed node and npm return to the server directory we created earlier. Now we can install express which is a lightweight framework for creating REST APIs.
npm install express --save

Create a file called index.js using your editor of choice. I used nano.
nano index.js

Paste the following:

javascript
// import the express module and create the express app
const express = require('express');
const app = express();
// install middleware that can encode the payload
app.use(express.urlencoded({extended:false})); 
// create an array to hold the environmental data
const data = []; 
// End points for the web service
//list entries
app.get('/api/environment/entries', (req,res) => {
    res.send(data); //Just send at empty array for now
} );
// create a web server, running on your port of choice or 3000
const port = process.env.PORT || 3000;
app.listen(port,() => {
    console.log(Listening on port ${port});
} );

This server will respond to HTTP GET requests at the /api/environment/entries endpoint listening on port 3000.

Start the node server
node index.js

Open your browser and go to
http://raspberrypi:3000/api/environment/entries

The result will not be very exciting as you will just see an empty array returned in the browser. However, give yourself a pat on the back. You have created your first fledgling web service!

Comments and sharing

4 min read

Today's article is a bit of fun. We are looking at the four levels of styling a simple logon dialog. These UI components are pretty ubiquitous. Here are a few examples of HTML logon dialogs

Level 1 - basic styling

They all share the same elements, at the minimum two input boxes, an OK button and usually a cancel button. Sometimes there are labels next to each input box. Other times placeholder text is shown in the input controls which gets replaced with whatever you type into the input control. In addition there is often a link to reset the password should it be forgotten.

With this in mind our logon dialog will have two input controls with placeholder text, a single button and a link to reset a forgotten password. Let's get to work. Our level 1 logon dialog will be vanilla. Some HTML and very little CSS. The CSS is there just to layout the control on the page. Here is our basic HTML.

html
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>Login</title>
		<meta name="description" content="Login to your account">
		<meta name="author" content="Jonathan">
		<link rel="stylesheet" href="css/styles.css?v=1.0">
	</head>
	<body>
		<div class="container">
			<div class="log-form">
				<h2>Login to your account</h2>
				<form>
					<input type="text" title="username" placeholder="username" />
					<input type="password" title="password" placeholder="password" />
					<button type="submit" class="btn">Login</button>
					<a class="forgot" href="#">Forgot Username?</a>
				</form>
			</div>
		</div>
	</body>
</html>

Nothing out of the ordinary here. We have defined a container div to allow it to be centred on the page. Inside this div we have another div which holds a standard form element. The form element has two input tags, a button and an anchor. All nice and simple. Let's now take a look at the CSS

css
.container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
}
form {
  width: 100%;
}
input {
  display: block;
  width: 100%;
  margin-bottom: 2em;
  padding: .5em 0;
}
.btn {
  padding: .5em 2em;
}

The container div is styled to fit the whole browser and uses the flex layout to easily centre the logon dialog vertically and horizontally. Note the height and width need to be 100% for this to work. The rest of the CSS is concerned with adding padding and margins to space out the elements in the dialog. This is the result.

Level 1 logon dialog with minimal styling

Yes it is functional but does it look good? Not really. I'd score it a C and that's pushing it. The next thing to do is 'style it up'. Add colours and make it pop. The first thing to do is choose a colour scheme. It's Summer here in the UK at the moment and the sun is out so I'm thinking orange...let's get going onto level 2.

Level 2 - style it up

css
* {
  box-sizing: border-box;
}
body {
  background-color: #ff9800ad;
}
.container {
  align-items: center;
  display: flex;
  justify-content: center;
  height: 100%;
  width: 100%;
}
.log-form {
  position: relative;
  width: 40%;
  background: #fff;
  box-shadow: 0px 2px 5px rgba(0, 0, 0, .25);
}
form {
  width: 100%;
  padding: 2em;
}
h2 {
  color: rgb(255, 87, 34);
  font-size: 1.35em;
  display: block;
  width: 100%;
  text-transform: uppercase;
  padding: 1em;
  margin: 0;
  font-weight: 200;
}
input {
  display: block;
  width: 100%;
  margin-bottom: 2em;
  padding: .5em 0;
  border: none;
  border-bottom: 1px solid #eaeaea;
  padding-bottom: 1.25em;
  color: #757575;
}
.btn {
  display: inline-block;
  background: rgb(255, 87, 34);
  border: none;
  padding: .5em 2em;
  color: white;
  margin-right: .5em;
  box-shadow: inset 0px 1px 0px whitesmoke;
}
.forgot {
  display: flex;
  justify-content: flex-end;
  color: rgb(255, 87, 34);
  font-size: .75em;
  width: 100%;
  transition: color 0.2s ease-in 0s;
}
Level 2 logon dialog, hello sunshine

This is much better. We have a bright background with the dialog centred as before. The dialog has been lifted by introducing a shadow effect around it. The clunky inputs have been styled with a single clean line and the text has been given a deep orange colour to complement the background. The vanilla old skool button has been replaced with a solid orange rectangle with white text. This is all good but look what happens when we navigate around the dialog.

The default blue focus outlines do not look right with the new dialog theme. Luckily we can do something about that.

Level 3 - add some finesse

While the level 2 version of our dialog looked good, but in use the default browser behaviour let it down. So for the next level we are going to provide custom styling to handle the form interactivity. At the same time we are going to add some pleasing animation to really finesse our dialog.

The CSS focus, active and hover pseudo selectors have been added along with animated transitions when moving between state. To highlight the button when it has focus I have added a box-shadow to act as a 'focus ring' around the button. The link now adds an underline style when it has focus. Here is the complete CSS.

css
* {
  box-sizing: border-box;
}
body {
  background-color: #ff9800ad;
}
.container {
  align-items: center;
  display: flex;
  justify-content: center;
  height: 100%;
  width: 100%;
}
.log-form {
  position: relative;
  width: 40%;
  background: #fff;
  box-shadow: 0px 2px 5px rgba(0, 0, 0, .25);
}
form {
  width: 100%;
  padding: 2em;
}
h2 {
  color: rgb(255, 87, 34);
  font-size: 1.35em;
  display: block;
  width: 100%;
  text-transform: uppercase;
  padding: 1em;
  margin: 0;
  font-weight: 200;
}
input {
  display: block;
  width: 100%;
  margin-bottom: 2em;
  padding: .5em 0;
  border: none;
  border-bottom: 1px solid #eaeaea;
  padding-bottom: 1.25em;
  color: #757575;
  transition: border-bottom 0.2s ease-in 0s;
}
input:focus,
input:hover {
  outline: none;
  border-bottom: 1px solid darkorange;
}
.btn {
  display: inline-block;
  background: rgb(255, 87, 34);
  border: none;
  padding: .5em 2em;
  color: white;
  margin-right: .5em;
  box-shadow: inset 0px 1px 0px whitesmoke;
  transition-property: background,box-shadow;
  transition-duration: 0.1s;
  transition-timing-function: ease-in;
  box-shadow: none;
}
.btn:hover {
  background: rgba(255, 87, 34, 0.8);
}
.btn:focus {
  outline:none;
  box-shadow: 0px 0px 2px 2px rgba(191,54,12,0.6);
}
.btn:active {
  background: #bf360c;
  box-shadow: inset 0px 1px 1px #bf360c;
}
.forgot {
  display: flex;
  justify-content: flex-end;
  color: rgb(255, 87, 34);
  font-size: .75em;
  text-decoration-line: none;
  width: 100%;
  transition: color 0.2s ease-in 0s;
}
.forgot:focus {
  text-decoration-line: underline;
  outline: none;
}
.forgot:hover {
  color: rgba(255, 87, 34, 0.8);
}
.forgot:active {
  color: #bf360c;
}

Level 4 - animate it

I though it would be cool to have a bouncing effect when the page is loaded. So the dialog jumps up and bounces 'down' onto the screen. This is fairly straightforward to do using animation keyframes.

The animation is referenced in the log-form class by supplying the name and duration. This tells the animation what element it is going to animate.

css
.log-form {
  animation-duration:1s;
  animation-name: bounce;
  width: 40%;
  background: #fff;
  box-shadow: 0px 2px 5px rgba(0, 0, 0, .25);
}

Here the animation is called bounce, the timing function allows you to define how the animation moves. Details here. Next you define the animation using the @keyframes keyword in your CSS file.

css
@keyframes bounce {
  0%   { transform: scale(1,1)    translateY(0); }
  10%  { transform: scale(1.1,.9) translateY(0); }
  30%  { transform: scale(.9,1.1) translateY(-100px); }
  50%  { transform: scale(1,1)    translateY(0); }
  57%  { transform: scale(1,1)    translateY(-7px); }
  64%  { transform: scale(1,1)    translateY(0); }
  100% { transform: scale(1,1)    translateY(0); }
}

The @keyframes keyword defines to do and when to do it. So in the example above at 10% we are squatting down to jump by making the dialog shorter and fatter. At 30% the dialog jumps by springing up. In doing so it becomes thinner and taller. At halfway we land on the ground before doing a little bounce after landing. This makes more sense seen in slow motion followed by the faster version.

The transform property allows you to rotate, scale, skew or translate(move) an element. In this case we are using a combination of scale and translate.

Here is the full CSS

css
* {
  box-sizing: border-box;
}
body {
  background-color: #ff9800ad;
}
.container {
  align-items: center;
  display: flex;
  justify-content: center;
  height: 100%;
  width: 100%;
}
.log-form {
  animation-duration:1s;
  animation-name: bounce;
  animation-timing-function: ease;
  width: 40%;
  background: #fff;
  box-shadow: 0px 2px 5px rgba(0, 0, 0, .25);
}
@keyframes bounce {
  0%   { transform: scale(1,1)    translateY(0); }
  10%  { transform: scale(1.1,.9) translateY(0); }
  30%  { transform: scale(.9,1.1) translateY(-100px); }
  50%  { transform: scale(1,1)    translateY(0); }
  57%  { transform: scale(1,1)    translateY(-10px); }
  64%  { transform: scale(1,1)    translateY(0); }
  100%  { transform: scale(1,1)    translateY(0); }
}
form {
  width: 100%;
  padding: 2em;
}
h2 {
  color: rgb(255, 87, 34);
  font-size: 1.35em;
  display: block;
  width: 100%;
  text-transform: uppercase;
  padding: 1em;
  margin: 0;
  font-weight: 200;
}
input {
  display: block;
  width: 100%;
  margin-bottom: 2em;
  padding: .5em 0;
  border: none;
  border-bottom: 1px solid #eaeaea;
  padding-bottom: 1.25em;
  color: #757575;
  color: rgb(255, 87, 34);
  transition: border-bottom 0.2s ease-in 0s;
}
input:focus,
input:hover {
  outline: none;
  border-bottom: 1px solid darkorange;
}
.btn {
  display: inline-block;
  background: rgb(255, 87, 34);
  border: none;
  padding: .5em 2em;
  color: white;
  margin-right: .5em;
  box-shadow: inset 0px 1px 0px whitesmoke;
  transition-property: background,box-shadow;
  transition-duration: 0.1s;
  transition-timing-function: ease-in;
  box-shadow: none;
}
.btn:hover {
  background: rgba(255, 87, 34, 0.8);
}
.btn:focus {
  outline:none;
  -webkit-box-shadow: 0px 0px 2px 2px rgba(191,54,12,0.6);
  -moz-box-shadow: 0px 0px 2px 2px rgba(191,54,12,0.6);
  box-shadow: 0px 0px 2px 2px rgba(191,54,12,0.6);
}
.btn:active {
  background: #bf360c;
  box-shadow: inset 0px 1px 1px #bf360c;
}
.forgot {
  display: flex;
  justify-content: flex-end;
  color: rgb(255, 87, 34);
  font-size: .75em;
  text-decoration-line: none;
  width: 100%;
  transition: color 0.2s ease-in 0s;
}
.forgot:focus {
  text-decoration-line: underline;
  outline: none;
}
.forgot:hover {
  color: rgba(255, 87, 34, 0.8);
}
.forgot:active {
  color: #bf360c;
}

So there we have it. Zero to hero in four steps. Enjoy!

Comments and sharing

2 min read

This data structure is an important one to know. A Binary Search Tree allows you to maintain a data set in sorted order. This in turn allows you efficiently locate data items. If you would were to use a standard array you would need to sort it every time you add a new data item. Not so with the BST. So with this in mind it must be pretty tricky to implement one, yes? It's actually quite straightforward. Let us dive in.

Each node in the BST holds some data which can be compared. This is important because it is this that enables data to be chunked or grouped based on the notion that one node is greater than the other.

A simple Binary Search Tree

Our data set looks like this 5,2,6,9,1,3,4.

In the example above 5 is the first item to be added. There is nothing in the tree to start with so the root contains 5. Next up in our list is 2. We would examine the first(root) node and ask ourselves this question "Is our new value greater or less than the current node?". Here 2 is less than 5 so it is placed in the left-hand side of the root node. Next up is 6. Again we would look at the first node(the root) and determine that 6 is greater than 5 and therefore place it in the right-hand side of the root node. Now our root node has two children 2 and 6. Now if we want to add the value 9 we look at the root, 9 is greater than 5 so we will place it on the right-hand side. However we can't do this because it already has the value 6. Now we look at node containing 6. 9 is greater than 6 so 9 is placed in the right-hand side of the node that contains 6, and so on...

Using this information we can define a Java class to represent a node in a BST.

java
public class BSTNode {
    public int data;
    public left;
    public right;
    public BSTNode(int value) {
        data = value;
        left = null;
        right = null;
    }
}

The BSTNode class is very simple. It has three public members. One to hold the data, in this case to keep things easy it is just an integer number for easy comparison. The other two hold the left and right child nodes. When the class is constructed the data value is passed in and set. Now to create the tree class itself and a method to add a value to the tree.

java
public class BinarySearchTree {
	public BSTNode root;
	public BinarySearchTree() {
		root = null;
	}
	/**
	 * Add a new node
	 * @param value The node value
	 * @return The new node
	 */
	public BSTNode add(int value) {
		// Create the new node
		BSTNode newNode = new BSTNode(value);
		// If there is no root then create and return
		if (this.root == null) {
			this.root = newNode;
			return this.root;
		}
		//Recurse through the tree and find the one where the data should be set
		BSTNode node = nextNode(this.root, value);
		if (value < node.data) {
			node.left = newNode;
		}
		else {
			node.right = newNode;
		}
		return newNode;
	}
	
	/**
	 * Get the next node that has does not have children
	 * @param node The current node
	 * @param value The value to be compared against the node's data value
	 * @return The node
	 */
	private BSTNode nextNode(BSTNode node, int value) {
		boolean leftNode = value < node.data;
		if (leftNode && node.left != null) {
			return nextNode(node.left, value);
		} else if (!leftNode && node.right != null) {
			return nextNode(node.right, value);
		}
		return node;
	}
}

In order to effectively traverse the tree I have implemented a recursive function which drills down into each child comparing the value as it goes and when it find the last correct node that does not have left/right child node it returns. The calling function then sets the correct class member left or right depending on the value.

Let's test our BST. We are going to add a unit test to ensure that the tree has been built correctly.

java
import static org.junit.Assert.*;  
import org.junit.Test;
public class TestBinarySearchTree {
	@Test
	public void testAdd() {
		// 5,2,6,9,1,3,4
		BinarySearchTree tree = new BinarySearchTree();
		// Add the root 5
		BSTNode root = tree.add(5);
		assertEquals(root, tree.root);
		// Add 2
		BSTNode node2 = tree.add(2);
		assertEquals(root.left, node2);
		// Add 6
		BSTNode node6 = tree.add(6);
		assertEquals(root.right, node6);
		// Add 9
		BSTNode node9 = tree.add(9);
		assertEquals(node6.right, node9);
		// Add 1
		BSTNode node1 = tree.add(1);
		assertEquals(node2.left, node1);
		// Add 3
		BSTNode node3 = tree.add(3);
		assertEquals(node2.right, node3);
		// Add 4
		BSTNode node4 = tree.add(4);
		assertEquals(node3.right, node4);
	}
}

Here we are checking that each node is placed correctly in the tree.

Comments and sharing