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 BinaryTree.java

69 thoughts on “Binary Tree in Java”

  1. 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. Derek,

    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.

    1. 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. 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. 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.

    Thanks

    1. 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.

  5. 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……

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

  7. 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.

    1. Hi Pat,

      I’m glad you found it useful. Using recursion is the normal way to traverse trees. You could do it in other ways, but I think this is the most straight forward.

  8. 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!

  9. 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.

  10. 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.

  11. 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.

  12. 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,
    Thanks

    1. 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?

  13. 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;
    return;
    }
    focusNode = focusNode.leftChild;
    } else {
    // right branch
    if(focusNode.rightChild == null) {
    focusNode.rightChild = newNode;
    return;
    }
    focusNode = focusNode.rightChild;
    }
    }
    }
    }

  14. 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..

    EX:

    LeftSide

    25
    30

    RightSide
    15
    75

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

    Thank you sir 🙂

      1. thank you sir 🙂

        another, how can I check if my binary tree is empty or not?

        I’m currently thinking of writing a class isEmpty() to check whether my BST is empty or not before I proceed in removing some nodes.
        And I dont know how 🙁

        (I’m currently watching the 2nd part of your tutorial about Binary Tree)

        thank you again Sir 🙂

          1. Almost finished with my codes sir 🙂

            Thank you very much for your tutorial videos and quick responses Sir 🙂
            It was really a great help~

            God bless you sir 🙂

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

  16. 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

  17. 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.

    Allyn

      1. Thanks. I am also looking into learning some material related to Graphs data structures. Do you have any ?

        Allyn

  18. 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.

  19. 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.

  20. 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?

  21. 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. Required fields are marked *