Binary Tree in Java

Binary Tree in JavaWelcome 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

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


			// Visit the currently focused on node


			// Traverse the right node




	public void preorderTraverseTree(Node focusNode) {

		if (focusNode != null) {





	public void postOrderTraverseTree(Node focusNode) {

		if (focusNode != null) {





	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");



class Node {

	int key;
	String name;

	Node leftChild;
	Node rightChild;

	Node(int key, String name) {

		this.key = key; = name;


	public String toString() {

		return name + " has the key " + key;

		 * return name + " has the key " + key + "\nLeft Child: " + leftChild +
		 * "\nRight Child: " + rightChild + "\n";



69 Responses to “Binary Tree in Java”

  1. Punit says:

    Hi Darek,
    i didn’t yet covered all you ds videos but just curious to know, are you also gonna cover index search in depth?

  2. Steve says:


    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.

    • Derek Banas says:

      Thank you very much 🙂 Yes, a binary search tree doesn’t have duplicate nodes. I’m constantly trying to improve my videos and I calue the input. I’ll do my best to get more code on the screen at once.

  3. Bob says:

    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

  4. Santosh says:

    Hi Derek,

    I’m new to Java but having looked at this video I must stay.. The vid is awesome. Indeed very useful for a new starter like me.


  5. Rajya says:

    Awesome tutorial! Please keep up the great work!

    • Derek Banas says:

      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.

  6. Joseph says:

    Hi sir i found the video very useful but i would be happy if u could lemme know how to find the path of a node in the tree which we are searching for……

  7. Ash says:

    I am new to Binary Tree and was sweating over it for couple of days, your videos are awesome. Perfect!!! Thanks a lot

  8. Patrick G says:

    In this code you sort them with integers, can you show a way to sort with strings instead?

  9. Pat says:

    Hi Derek, Thanks for the article.

    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.

  10. Anonymous says:

    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!

  11. Anonymous says:

    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.

  12. Anonymous says:

    Hi Derek, Thank you for such a good explanation of this series.

    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.

  13. Jaroslav says:

    Thanks for video. It is good

  14. Harsh Shah says:

    Hi Derek ! Great tutorials overall.

    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.

    Kindly update the title probably.

  15. Pip_Squeak says:

    Hi Derek,

    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,

    • Derek Banas says:

      You’re very welcome 🙂 Everything is dependent on keys with a binary tree. A family tree wouldn’t work very well because you only have 2 nodes coming off of each other node. Does that make sense?

  16. Dmytro says:

    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 🙂

    Here my slightly simplified version:

    public void addNode(int key, String value) {
    Node newNode = new Node(key, value);
    if(root == null) {
    root = newNode;
    } else {
    Node focusNode = root;
    while(true) {
    if(key < focusNode.key) {
    // left branch
    if(focusNode.leftChild == null){
    focusNode.leftChild = newNode;
    focusNode = focusNode.leftChild;
    } else {
    // right branch
    if(focusNode.rightChild == null) {
    focusNode.rightChild = newNode;
    focusNode = focusNode.rightChild;

  17. Honey Mae says:

    Sir, I would like to ask how can I display all of my inputs categorized if it belongs to the Right side or the Left side..





    (something like that sir)
    I’m still learning and I’m kinda having a hard time figuring it out.

    Thank you sir 🙂

  18. Brenda says:

    The code doesn’t work. I get a java.lang.NoSuchMethodError in line 009.

  19. sunny says:

    Awesome videos. I am a beginner with Java and these videos are very helpful

  20. GeLiGeLu says:

    Do you have a link to the video on youtube or another mirror? It seems to be missing for me….

  21. Anonymous says:

    Instead of finding the specific key, how would you display just the whole tree with the strings?

  22. clinton says:

    Hi i am wondering how a text file could be read into this example and update the values in the tree this way. Cheers

  23. Dayalan says:

    Sir your tutorials are awesome…

    I got a “B-” for OOPs Semester Examination in University of Colombo, Sri Lanka for Bachelor of IT…

    I didn’t attend any classes for this… I just followed your video tutorials and now I’m keep going with your Java tutorials for next semester Java Examination….

    Thanks a lot….
    You are doing great job for us………………

    I’ll keep watching your videos

  24. Allyn Smith says:

    Hi Thanks for really taking time and helping others.

    I do have really time experience of 8 yrs of programming experience, I still struggle to get the concepts of data structures and algorithms in the right.

    This video did not only help me in clearly understand the concepts. It boasted my confidence a lot. I genuinely thankful for your videos.

    Hopefully able to crack the coding interviews with the new arsenal in my kitty.


  25. Pritam Banerjee says:

    I just Love your videos. It so quickly walks through the concepts.

  26. Nikhil says:

    Good video,but you should have mentioned in the beginning of the video what do higher and lower values of keys have relationship with the Node hierarchy.

  27. Rahul says:

    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.

  28. Ruby says:

    Hi !
    loved the binary tree video!

    just a question, how did you improve your programming?
    I cant do a whole program on my own like you 🙁
    any tips?

  29. Amathia says:

    Hat’s off to you sir.
    Thanks a lot.

  30. Saurabh Arora says:

    Awesome video

  31. Jerry says:

    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?

Leave a Reply

Your email address will not be published.