Welcome to my tutorial on the Binary Tree in Java. On average a tree is more efficient then other data structures if you need to perform many different types of operations.

In this tutorial I’ll show you what a binary tree is, and how to create, add, traverse and find nodes. I’ll also explain all the terminology used when describing tree structures. We’ll cover nodes, paths (edges), traversing and much more.

If you like videos like this, it helps to tell Google+ with a click [googleplusone]

Code From the Video

Binary Tree in Java BinaryTree.java

public class BinaryTree {
Node root;
public void addNode(int key, String name) {
// Create a new Node and initialize it
Node newNode = new Node(key, name);
// If there is no root this becomes root
if (root == null) {
root = newNode;
} else {
// Set root as the Node we will start
// with as we traverse the tree
Node focusNode = root;
// Future parent for our new Node
Node parent;
while (true) {
// root is the top parent so we start
// there
parent = focusNode;
// Check if the new node should go on
// the left side of the parent node
if (key < focusNode.key) {
// Switch focus to the left child
focusNode = focusNode.leftChild;
// If the left child has no children
if (focusNode == null) {
// then place the new node on the left of it
parent.leftChild = newNode;
return; // All Done
}
} else { // If we get here put the node on the right
focusNode = focusNode.rightChild;
// If the right child has no children
if (focusNode == null) {
// then place the new node on the right of it
parent.rightChild = newNode;
return; // All Done
}
}
}
}
}
// All nodes are visited in ascending order
// Recursion is used to go to one node and
// then go to its child nodes and so forth
public void inOrderTraverseTree(Node focusNode) {
if (focusNode != null) {
// Traverse the left node
inOrderTraverseTree(focusNode.leftChild);
// Visit the currently focused on node
System.out.println(focusNode);
// Traverse the right node
inOrderTraverseTree(focusNode.rightChild);
}
}
public void preorderTraverseTree(Node focusNode) {
if (focusNode != null) {
System.out.println(focusNode);
preorderTraverseTree(focusNode.leftChild);
preorderTraverseTree(focusNode.rightChild);
}
}
public void postOrderTraverseTree(Node focusNode) {
if (focusNode != null) {
postOrderTraverseTree(focusNode.leftChild);
postOrderTraverseTree(focusNode.rightChild);
System.out.println(focusNode);
}
}
public Node findNode(int key) {
// Start at the top of the tree
Node focusNode = root;
// While we haven't found the Node
// keep looking
while (focusNode.key != key) {
// If we should search to the left
if (key < focusNode.key) {
// Shift the focus Node to the left child
focusNode = focusNode.leftChild;
} else {
// Shift the focus Node to the right child
focusNode = focusNode.rightChild;
}
// The node wasn't found
if (focusNode == null)
return null;
}
return focusNode;
}
public static void main(String[] args) {
BinaryTree theTree = new BinaryTree();
theTree.addNode(50, "Boss");
theTree.addNode(25, "Vice President");
theTree.addNode(15, "Office Manager");
theTree.addNode(30, "Secretary");
theTree.addNode(75, "Sales Manager");
theTree.addNode(85, "Salesman 1");
// Different ways to traverse binary trees
// theTree.inOrderTraverseTree(theTree.root);
// theTree.preorderTraverseTree(theTree.root);
// theTree.postOrderTraverseTree(theTree.root);
// Find the node with key 75
System.out.println("\nNode with the key 75");
System.out.println(theTree.findNode(75));
}
}
class Node {
int key;
String name;
Node leftChild;
Node rightChild;
Node(int key, String name) {
this.key = key;
this.name = name;
}
public String toString() {
return name + " has the key " + key;
/*
* return name + " has the key " + key + "\nLeft Child: " + leftChild +
* "\nRight Child: " + rightChild + "\n";
*/
}
}

COMMENT: Your videos are incredible! Thank you for producing them and keep them coming. The pace is perfect and just the right amount of subject material for each one.

QUESTION: The binary tree examples will only work if there are no duplicate keys, correct?

SUGGESTION: I don’t want to make you change your format, but I would prefer it if you would skip the blank lines between lines of code, so that there would always be more code visible on the screen. It’s probably just me.

Hello Derek, thanks for everything you have done! I just have one question. I see that in your node class you have made it so that every node has a reference to its left and right child. Don’t nodes also need references to their parent nodes?
Just a question… and thanks

Thank you 🙂 I have videos planned out over a year in advance. I look forward to the days in which I can make game tutorials while covering electronics. I have been working towards that goal for 5 years.

One question: Would it be helpful to know how to traverse the tree in order without using recursion? And, how would I go about doing that? Right now, I think i might have to use a stack since it seems like a depth first traversal but I am not sure on the intricacies. Would love to hear your thoughts.

Hello,
Very nice presentation and explanation of the code! I like it. However, you are talking about Binary Search Tree, which belongs to Binary Tree group. The students can be lost when we talk for ex. about Heap Tree which is also a Binary Tree but with other properties or AVL, Red-Black tree etc. Again – very good presentation, but can be misleading for the beginners.
Best wishes!

Hey Derek, great tutorial. I do have one question though. How would you implement an 2 dimensional array into a tree? I’m having trouble trying to figure out how to implement a table of keys into a tree.

Since I am still new to Java programming and binary tree, I could not understand why the root’s members can be updated with the value assigned to parent’s member even though you never declare “root = parent”?

When I went through debugging, I saw the left or right child of the root are replaced with the key assigned to parent’s child.

However , I’d like to point out that your code is implementing a binary search tree and not a binary tree. A binary search tree is just a special case of a binary tree where the condition of left child being smaller than the node and right child being larger is satisfied.

Thanks so much for the video. I was wondering if you could offer some guidance on how to implement a family tree using a Binary Tree. For this to work, how would I implement an Ancestor, partner, sibling – child?
Any help would be appreciated,
Thanks

Hello Derek. All you tutorials are excellent!
But here in this one I wonna to point you to some improvement.

In the addNode method there is no need to use extra ‘parent’ variable, you can survive with ‘focusNode’ only. Its quite important to have as clean implementation as possible especially with recursions when you need to model stack calls in your brains 🙂

Hi Derek,
Thank you for the great video explaining implementation of Binary Search Tree. I just need a clarification regarding the terminology. From my knowledge, A Binary Search Tree is different from Binary Tree with the condition that all the left node are less than or equal to root and the right nodes are greater than the root node.

When you try to find a node that isn’t in the tree, it throws a NullPointerException in main and findNode. Not sure why it does that in main, but I do understand why in findNode (obviously). Is there a way to correctly handle the exception?