Learn Binary search trees in 20 minutes 🔍

Поделиться
HTML-код
  • Опубликовано: 4 окт 2024
  • Binary search tree data structures and algorithms java
    #binary #search #tree

Комментарии • 91

  • @BroCodez
    @BroCodez  2 года назад +151

    WARNING: THIS IS AN EXTREMELY DIFFICULT TOPIC, DO NOT GET DISCOURAGED :)
    public class Main {
    public static void main(String[] args) {

    //Binary Search Tree = A tree data structure, where each node is greater than it's left child,
    // but less than it's right.

    // benefit: easy to locate a node when they are in this order

    // time complexity: best case O(log n)
    // worst case O(n)

    // space complexity: O(n)

    BinarySearchTree tree = new BinarySearchTree();

    tree.insert(new Node(5));
    tree.insert(new Node(1));
    tree.insert(new Node(9));
    tree.insert(new Node(2));
    tree.insert(new Node(7));
    tree.insert(new Node(3));
    tree.insert(new Node(6));
    tree.insert(new Node(4));
    tree.insert(new Node(8));

    tree.display();
    }
    }
    public class BinarySearchTree {
    Node root;

    public void insert(Node node) {

    root = insertHelper(root, node);
    }
    private Node insertHelper(Node root, Node node) {

    int data = node.data;

    if(root == null) {
    root = node;
    return root;
    }
    else if(data < root.data) {
    root.left = insertHelper(root.left, node);
    }
    else {
    root.right = insertHelper(root.right, node);
    }

    return root;
    }
    public void display() {
    displayHelper(root);
    }
    private void displayHelper(Node root) {

    if(root != null) {
    displayHelper(root.left);
    System.out.println(root.data);
    displayHelper(root.right);
    }
    }
    public boolean search(int data) {
    return searchHelper(root, data);
    }
    private boolean searchHelper(Node root, int data) {

    if(root == null) {
    return false;
    }
    else if(root.data == data) {
    return true;
    }
    else if(root.data > data) {
    return searchHelper(root.left, data);
    }
    else {
    return searchHelper(root.right, data);
    }
    }
    public void remove(int data) {

    if(search(data)) {
    removeHelper(root, data);
    }
    else {
    System.out.println(data + " could not be found");
    }
    }
    private Node removeHelper(Node root, int data) {

    if(root == null) {
    return root;
    }
    else if(data < root.data) {
    root.left = removeHelper(root.left, data);
    }
    else if(data > root.data) {
    root.right = removeHelper(root.right, data);
    }
    else { // node found
    if(root.left == null && root.right == null) {
    root = null;
    }
    else if(root.right != null) { //find a successor to replace this node
    root.data = successor(root);
    root.right = removeHelper(root.right, root.data);
    }
    else { //find a predecessor to replace this node
    root.data = predecessor(root);
    root.left = removeHelper(root.left, root.data);
    }
    }
    return root;
    }
    private int successor(Node root) { //find least value below the right child of this root node
    root = root.right;
    while(root.left != null){
    root = root.left;
    }
    return root.data;
    }
    private int predecessor(Node root) {//find greatest value below the left child of this root node
    root = root.left;
    while(root.right != null){
    root = root.right;
    }
    return root.data;
    }
    }
    public class Node {
    int data;
    Node left;
    Node right;

    public Node(int data) {
    this.data = data;
    }
    }

    • @RinInABin
      @RinInABin 2 года назад +13

      I needed that warning :)
      Keep up the good work man

    • @vinsmokesanji7629
      @vinsmokesanji7629 2 года назад

      thank you bro

    • @spenzr6920
      @spenzr6920 2 года назад

      I doubt that I will get discouraged if I study from a teacher like you 👍
      And i hope no one else gets discouraged too

    • @joyceasante8292
      @joyceasante8292 Год назад +2

      (Coding along, line by line)
      public class Main{
      public static void main(String[]args){
      BinarySearchTree tree = new BinarySearchTree();
      tree.insert(new Node(5));
      tree.insert(new Node(1));
      tree.insert(new Node(9));
      tree.insert(new Node(2));
      tree.insert(new Node(7));
      tree.insert(new Node(3));
      tree.insert(new Node(6));
      tree.insert(new Node(4));
      tree.insert(new Node(8));
      tree.remove(0);
      tree.display();
      }
      }
      ****************************
      public class BinarySearchTree
      {
      Node root;
      public void insert (Node node)
      {
      root = insertHelper (root, node);
      }
      private Node insertHelper (Node root, Node node)
      {
      int data = node.data;
      if (root == null)
      {
      root = node;
      return root;
      }
      else if (data < root.data)
      {
      root.left = insertHelper (root.left, node);
      }
      else
      {
      root.right = insertHelper (root.right, node);
      }
      return root;
      }
      public void display ()
      {
      displayHelper (root);
      }
      private void displayHelper (Node root)
      {
      if (root != null)
      {
      displayHelper (root.left);
      System.out.println (root.data);
      displayHelper (root.right);
      }
      }
      public boolean search (int data)
      {
      return searchHelper (root, data);
      }
      private boolean searchHelper (Node root, int data)
      {
      if (root == null)
      {
      return false;
      }
      else if (root.data == data)
      {
      return true;
      }
      else if (root.data > data)
      {
      return searchHelper (root.left, data);
      }
      else
      {
      return searchHelper (root.right, data);
      }
      }
      public void remove (int data)
      {
      if (search (data))
      {
      removeHelper (root, data);
      }
      else
      {
      System.out.println (data + " could not be found");
      }
      }
      private Node removeHelper (Node root, int data)
      {
      if (root == null)
      {
      return root;
      }
      else if (data < root.data)
      {
      root.left = removeHelper (root.left, data);
      }
      else if (data > root.data)
      {
      root.right = removeHelper (root.right, data);
      }
      else
      {
      if (root.left == null && root.right == null)
      {
      root = null;
      }
      else if (root.right != null)
      {
      root.data = successor (root);
      root.right = removeHelper (root.right, root.data);
      }
      else
      {
      root.data = predecessor (root);
      root.left = removeHelper (root.left, root.data);
      }
      }
      return root;
      }
      private int successor (Node root)
      {
      root = root.right;
      while (root.left != null)
      {
      root = root.left;
      }
      return root.data;
      }
      private int predecessor (Node root)
      {
      root = root.left;
      while (root.right != null)
      {
      root = root.right;
      }
      return root.data;
      }
      }
      ************************
      public class Node{
      int data;
      Node left;
      Node right;
      public Node(int data){
      this.data = data;
      }
      }

    • @zenovak5177
      @zenovak5177 Год назад

      no worries bro, you teach good. I am following along in C#
      One thing to point out when using recurssions, name your parameters a bit differently than your fields. instead of insertHelper(Node root,....) do insertHelper(Node _root). Makes it easier in the eyes

  • @DassVeryGood
    @DassVeryGood Год назад +88

    This semester my professor is terrible teacher and of course it had to be a subject that matters most in this line of work. So I just want to say thank you for saving me in this class. Even if I don’t do well in the class (it’s the most convoluted, intimidating, and egregious class I’ve ever taken and been graded on) I’m still thankful that someone can explain this concept in a straightforward manner.

    • @unodos2647
      @unodos2647 Год назад +10

      i feel you dude. data structures and algorithms is rough, especially when the class is big and the professor is...okay at best.

    • @hk254lyt8
      @hk254lyt8 5 месяцев назад

      How did you do?

    •  Месяц назад

      You programmer now

  • @Ran_cnc_3d
    @Ran_cnc_3d 2 года назад +55

    Bro ,somewhere on 8-10 minutes I saw orcs from Warcraft 3, running on my screen. I recognized myself in childhood sitting near my old Pentium 4...Then NPC bots came and crush my base , I was so angry! And then I woke up. Such a strange dream.

  • @super-_-chill1812
    @super-_-chill1812 10 месяцев назад +10

    Funny enough I took the Data Structure course a year ago and only understood trees today. Thank you Bro Code🙏🙏

  • @АлександрФельдман-й8в

    Отлично! Жду ещё видео про деревья.

    •  Месяц назад

      Your Russian you don't brocode you're born to code

  • @anonimanonim1223
    @anonimanonim1223 2 года назад +12

    I used debugger in Eclipse IDE to understand how a program works. Very useful tool to learn programming if you do not know how something works.

  • @rabbit3711
    @rabbit3711 Год назад +5

    Bro, you are pro, the way you teach this topics is just amazing. I thought it will be imposible for me to understand trees, but you make it possible bro, thanks for what you dooo :D

  • @felifrit
    @felifrit 11 месяцев назад +2

    Best tutorial channel out there, thanks a ton

  • @eugenezuev7349
    @eugenezuev7349 26 дней назад

    sweet but tough
    as I can see you are not so bad at gardening, thanks Bro

  • @stephanieezat-panah7750
    @stephanieezat-panah7750 2 года назад +2

    This was *excellent*, thank you!

  • @APDesignFXP
    @APDesignFXP 2 года назад +1

    Bro tbh, as someone who about to start SE, it's fascinating to me how recursion used in 8:00. Truly am a geek.

  • @28santagabo
    @28santagabo Год назад +2

    I learned a ton with your videos

  • @PIRAKAS666
    @PIRAKAS666 Год назад +10

    shits mad hard bro

  • @Luna-mu1wm
    @Luna-mu1wm 6 месяцев назад

    this is actually a really good covering video ! nice

  • @lukhanyokalashe1906
    @lukhanyokalashe1906 5 месяцев назад

    Thanks Bro, my Proff decided to skip this part but then in interviews i know they ask such question !! btw implementing in c# but we suing generics instead of int but implementation is the same. from SA

  • @jeffisded1222
    @jeffisded1222 4 месяца назад +1

    Doesn't your remove method not actually remove the node, but updates the value to the successor/predecessor's value, then deletes the successor/predecessor? I feel like that is a cheese way of "removing" the node.
    I guess it works in this example though.

  • @kartikeyayadav1549
    @kartikeyayadav1549 Месяц назад

    A binary tree is a tree where each node has no more than 2 children. Root node should be greater than left child and less than right child. Leftmost child must have the least value. Right most child should have the most value. This arrangement helps with quick lookup. Big O logn

  • @Juliana-cx7qq
    @Juliana-cx7qq Год назад +2

    bro code I promise if I remember one day I owe you a meal or a coffee, in a future when I have more money.... god I LOVE YOU MAN!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  • @marinhoconservador
    @marinhoconservador Год назад +1

    Love you Bro, from Brazil

  • @antonionotbanderas9775
    @antonionotbanderas9775 4 месяца назад

    I'm only at 2:47 and need to implement these nested left right classes for my interactive fiction project.
    I'm happy with nodejs termux, yeah in 2024 everyone is making mobile games 🤣

  • @kvelez
    @kvelez Год назад +2

    Great video, always appreciate your kind words.
    public class App {
    public static void main(String[] args) {
    BinarySearchTree tree = new BinarySearchTree();
    tree.insert(new Node(5));
    tree.insert(new Node(1));
    tree.insert(new Node(9));
    tree.insert(new Node(7));
    tree.insert(new Node(3));
    tree.insert(new Node(4));
    tree.insert(new Node(6));
    tree.insert(new Node(8));
    tree.remove(5);
    tree.display();
    System.out.println(tree.search(7));
    }
    }
    class Node{
    int data;
    Node left;
    Node right;
    public Node(int data){
    this.data = data;
    }
    }
    class BinarySearchTree{
    Node root;
    public void insert(Node node){
    root = insertHelper(root, node);
    }
    private Node insertHelper(Node root, Node node){
    int data = node.data;
    if (root == null){
    root = node;
    return root;
    } else if (data < root.data){
    root.left = insertHelper(root.left, node);
    } else {
    root.right = insertHelper(root.right, node);
    }
    return root;
    }
    public void display(){
    displayHelper(root);
    }
    private void displayHelper(Node root){
    if (root != null){
    displayHelper(root.left);
    System.out.println(root.data);
    displayHelper(root.right);
    }
    }
    public boolean search(int data){
    return serachHelper(root, data);
    }
    private boolean serachHelper(Node root, int data){
    if (root == null){
    return false;
    } else if (root.data == data){
    return true;
    } else if (root.data > data){
    return serachHelper(root.left, data);
    } else {
    return serachHelper(root.right, data);
    }
    }
    public void remove(int data){
    if (search(data)){
    removeHelper(root, data);
    } else{
    System.out.println( data + " could not be found.");
    }
    }
    public Node removeHelper(Node root, int data){
    if (root == null){
    return root;
    } else if (data < root.data){
    root.left = removeHelper(root.left, data);
    } else if (data > root.data){
    root.left = removeHelper(root.right, data);
    } else {
    if (root.left == null && root.right == null){
    root = null;
    }
    else if (root.right != null) {
    root.data = successor(root);
    root.right = removeHelper(root.right, data);
    }
    else{
    root.data = predecesor(root);
    root.left = removeHelper(root.left, data);
    }
    }
    return root;
    }
    private int successor(Node root){
    root = root.right;
    while (root.left != null){
    root = root.left;
    }
    return root.data;
    }
    private int predecesor(Node root){
    root = root.left;
    while (root.right != null){
    root = root.right;
    }
    return root.data;
    }
    }

  • @lightninginmyhands4878
    @lightninginmyhands4878 Год назад

    Great job. Thanks

  • @tasneemayham974
    @tasneemayham974 Год назад +3

    I have a question:
    Instead of making successor and predecessor methods, can't we write:
    else if(root.right != null) return root.right;
    else if(root.left != null) return root.left;
    In the end, if a node has only one child, then we directly connect its parent with the child. Does anyone think this works?

    • @XxbankerboomxX
      @XxbankerboomxX Год назад

      This is my solution: Find the parent of the node to remove, example we want to remove 5: parent.right= 5 is now parent.right.right = 6 and the new parent.right.left = null is the old parent.right.left = 4. In case the child was on the parent.left, just flip it around

    • @XxbankerboomxX
      @XxbankerboomxX Год назад

      Please tell me if you understood what i wrote i want to know if i explain well

    • @tasneemayham974
      @tasneemayham974 Год назад

      ​@@XxbankerboomxX I am sorry, for not replying fast. I am just trying to figure it out, and I am not getting it. I get traversals, inserting, searching, but I don't get deleting. I don't understand why we have to go through the whole process, and not just return the child.
      I am sorry for not responding, but I didn't want to tell you that I didn't quite grasp. However, I would really appreciate it if you do try to help me out here!!
      And great ThANK YOU!!

    • @XxbankerboomxX
      @XxbankerboomxX Год назад

      @@tasneemayham974 Hey no problem :) You can essentially return the child, but the parent might have two children, so if you return the right child, the left child is now left without a parent. Solution to this is to attach the left child as a child to the right child.

  • @TAPPED_Out
    @TAPPED_Out 2 года назад +3

    bro is R E L E L E N T L E S S

  • @johnwilliams-qn8mx
    @johnwilliams-qn8mx 8 месяцев назад +3

    I don't understand shit , your video is nice though

  • @stoiandelev12345678
    @stoiandelev12345678 Год назад +1

    Отлично обяснение

  • @thomas_1611
    @thomas_1611 Год назад

    cool video

  • @chillaestheticlove7437
    @chillaestheticlove7437 2 года назад +1

    Love you bro

  • @manishbhurtel8848
    @manishbhurtel8848 2 года назад +1

    Love from nepal

  • @MrLoser-ks2xn
    @MrLoser-ks2xn Год назад

    Thanks!

  • @gameGXT
    @gameGXT 2 года назад

    Super

  • @princeangelo7051
    @princeangelo7051 2 года назад

    Cool

  • @arniequeamaba6635
    @arniequeamaba6635 11 месяцев назад

    Bro was a legend

  • @luciddoggo5094
    @luciddoggo5094 Год назад +2

    I still dont get how to even make a tree, it feels like it just went from level 1 coding to level 30 in two videos. I understood everything b4 this

    • @Sammysapphira
      @Sammysapphira 2 месяца назад

      The tree is populated with the insert method

  • @baljeetsingh5813
    @baljeetsingh5813 2 года назад +2

    GOAT

  • @ricardotrejoruiz5776
    @ricardotrejoruiz5776 Год назад

    Probably the code misses when a value is insert two times... Or is it necessary to save any number even is inserted twice? I know is called binary tree but not binary list tree jajajaj

  • @scuffedwizard
    @scuffedwizard 4 дня назад

    You are a real fucking lifesaver I hope you know that

  • @minhct2511
    @minhct2511 2 года назад

    Love from VietNam

  • @sametsahin-eh3qj
    @sametsahin-eh3qj 8 месяцев назад

    THE GOAT

  • @AibekMurat-m2z
    @AibekMurat-m2z Год назад

    Bro really said Thorfinn☠

  • @x-yv9uv
    @x-yv9uv Год назад +1

    At 10:15 , When I Run this in a debugger the node traversal makes sense and it keeps running normally till it reaches the left most node of the tree and then i get an null node (root.left to the leftmost node with no children is null which makes sense) then it just skips to System.out.print statement without exiting the if statement ? why is that ? can someone walk me through if step by step ? shouldn't the print be outside the if statement ? it doenst make sense for me

    • @tasneemayham974
      @tasneemayham974 Год назад +2

      I believe this is the correct logic behind the code:
      So we have numbers from 1 till 9 and the root of the whole tree is 5, correct? (If you don't get why the root of the entire tree is 5, tell me). The traversal is called in-order.
      In-Order Traversal: is a process that displays the nodes of a BST in non-decreasing order and uses recursion.
      We start at the root of the tree and work our way towards the left. When all the left children are done, basically you reached the left-most child and the smallest data, we will encounter a null node and hence go back to the parent. Once we hit a node TWICE we will print the data of that node, and go to the right child, then take left-child and keep taking left until it's null and so on.
      So, we have 5 and to the left is 1. To the left of 1 there is null so we will round back and go to 1 again. Oooh we hit 1 TWICE so we print that and go to its right child which is 2. Go left, null and we encountered 2 again so print it, and go to the right. Now, it's 3 this is the first time I see 3 so we keep going left, but to the left of 3 there is null so we round back to the parent and we see 3 again. Print it. Go to right child it's 4. 4 is a leaf, so we go back we find 3(already printed), 2(already printed), 1(already printed), 5 this is the second time, so we print 5 and go to its right child.
      It's a lengthy reply. But I hope I made it clear.

    • @x-yv9uv
      @x-yv9uv Год назад

      @@tasneemayham974 Hey Tasneem thanks for the reply. The logic and everything you explained was perfect and i already understood that before but I think you made it even clearer and better. But my issues is with logic not being shown in the code itself, the code simply does it like for example:
      The part where you said " we will encounter a null node and hence go back to the parent." , How does that in work in Java ? all there is in the code is that root.left is passed as an argument back to the method and that there is a print statement right after it, other wise there are no elaboration or if statements, it just works which is why it's confusing me...
      can you tell me how did we hit a null node twice, as in where in the program does it say If(node visited twice) do (x) ?

    • @tasneemayham974
      @tasneemayham974 Год назад +1

      @@x-yv9uv You're welcome!!
      And I do apologize for not understanding your question first. But I get it now. Here's how the code works:
      REMARK: Keep in mind the process is recursive which means: Recursion 1 starts with the root node and doesn't end until all the left subtrees are traversed and the right subtrees are traversed. The traversal is done when we reach a null root in which case we will return which means go back to parent.
      Okay, we start with the root of the entire tree as that is the first time displayHelper() is called. This is the first recursion: Recursion1[5 is the root]. Every time you insert a root that is NOT null to the displayHelper() a recursion is started and doesn't end until all its subtrees are traversed. The first line calls displayHelper() with the root's left child as the new root. Now, 1 is the new root. Is it null? No? Recursion2 starts[1 is the root]. The left child of 1 is the new root. Is it null? Yes? Return Recursion2 which means now we are back to the root 1 and half of Recursion2 is over since we traversed its left tree and found null. We will now print the root's data. Third, assign the right child as a new root. Now, 3 is the new root. Is it null? No? Recursion3 starts[3 is the root]. Call displayHelper() again with the root's left child as the new root --> 2. Is it null? No? Recursion4 starts[2 is the root]. displayHelper() is called with 2's left child as the new root. Is it null? Yes? Return Recursion4 which means we are back to root 2 and half of Recursion4 is over. To complete the second half, we go to the right child and assign it as the new root. Is it null? Yes? Return Recursion4 which means we are back again to root 2 and all of Recursion4 is over.
      NOTE: If you add a print statement after the displayHelper(root.right), you will see that the leaf nodes are printed twice which means that when the recursion is OVER(the entire right tree is traversed).
      Now, we go back to Recursion3 which has a root of 3, and we are done half, hence print the root's data. Now, assign the right child of the root as the new root -> 4. Is it null? No? Recursion4 starts[4 is the root]. Go to the left child. Is it null? Yes? Return Recursion4 which means we go back to the parent. Thus, fully traversing the left subtree and we are left with the right. So half Recursion4 is done and we came across the root for the second time, print the root's data and assign its right child as the new root. Is it null? Yes? Return Recursion4 and now it's over as both subtrees are fully traversed. We hence go back to(return) Recursion3 with root 3. Recursion3 is also done and fully traversed. Return Recursion2 with root 1. Recursion2 is done and its left&right trees fully traversed. Return Recursion1 with root 5. Recursion1 is now half traversed. The Recursion is not over, but we did finish the left branches so now print the root's data and assign its right child as the new root.
      This is the best I could do with the explanation. If you understand, try to explain to me the right branch of the tree. Please tell me if I made anything vague, so that I re-explain. I hope you got it.

    • @tasneemayham974
      @tasneemayham974 Год назад +1

      @@x-yv9uv By the way, Sorry I forgot to add this. But this statement where I keep repeating if the root is null, then return the recursion, is present in the code as a reverse to if(root!=null). What I mean is the IDE understands that if the condition is not satisfied return the recursion. If you're not comfortable with that, you can write else{return;}
      Heyy, it's okay. Don't get upset if you don't get it at first. This is what it takes for us to be great coders ONE DAYYYY!!!!! Kudos to you, my friend!!!!!!!!!!!!!!!

    • @x-yv9uv
      @x-yv9uv Год назад

      @@tasneemayham974 Hey, Thanks for the reply, I think i kinda got it, running it again in NetBeans Debugger and keeping the if statement in mind, i think it kinda clicked in

  • @mensahtribeadventures2630
    @mensahtribeadventures2630 2 года назад

    🤓💪🏾💪🏾😎

  • @marke4246
    @marke4246 2 года назад +1

    A true sigma

  • @HousseinAlDroubi
    @HousseinAlDroubi 26 дней назад

    Good, what about you.

  • @jatoxo
    @jatoxo Год назад

    Is it technically still a valid binary tree if you have:
    . 3
    . / \
    . 2 5
    . / \
    . 1 4
    This way 4 is bigger than 2 and 2 is smaller than 3, so it should fit the definition, but if you were looking for 4 you would never find it

    • @hritwiknauriyal2254
      @hritwiknauriyal2254 Год назад +1

      I don't think you are ever able to insert 4 at that spot

    • @brenotanquista9543
      @brenotanquista9543 Год назад

      no

    • @mahaiye3903
      @mahaiye3903 Год назад +9

      4 is greater than 3, hence when you try to insert it, it would go down the right of 3, then left of 5
      . 3
      . / \
      . 2 5
      . / /
      . 1 4

    • @jarvisjackson4833
      @jarvisjackson4833 Год назад

      everything to the left of a root should be smaller, the root is 3 which is smaller than 4, it is not a binary search tree.

    • @anotheryoutuberperson38
      @anotheryoutuberperson38 10 месяцев назад

      No, 4 would be inserted to the right of the root, 3.

  • @felipemedrano5363
    @felipemedrano5363 2 года назад

    Hello Bro

  • @mrpipiskin4
    @mrpipiskin4 Год назад

    true chad

  • @MK-wc7sy
    @MK-wc7sy Год назад +1

    طيب لو اقولك نتزوج

    • @3bood_kr
      @3bood_kr Год назад

      يو💀💀

    • @MK-wc7sy
      @MK-wc7sy Год назад +1

      @@3bood_kr بشر كيف الاختبار

  • @thuydung7028
    @thuydung7028 2 года назад

    hi

  • @tsunningwah3471
    @tsunningwah3471 6 месяцев назад

    swxz!

  • @lequangnghi194
    @lequangnghi194 Год назад +2

    I have no idea how the displayHelper() works 🥲

    • @X0RZ0R
      @X0RZ0R Год назад +1

      At first I was also a bit boggled, would you like me to try and explain? I'm only asking cause I don't want to do it if you don't need it anymore 😂

    • @ricardotrejoruiz5776
      @ricardotrejoruiz5776 Год назад

      It works like composition. First it goings as deep as the composition can, then it will be start printing from the last to the beginning. Is really confusing until you get experience imaging how composition works :)