Test If A Binary Tree Is Height Balanced ("Balanced Binary Tree" on LeetCode)

แชร์
ฝัง
  • เผยแพร่เมื่อ 23 ส.ค. 2024
  • Free 5-Day Mini-Course: backtobackswe.com
    Try Our Full Platform: backtobackswe....
    📹 Intuitive Video Explanations
    🏃 Run Code As You Learn
    💾 Save Progress
    ❓New Unseen Questions
    🔎 Get All Solutions
    Question: Write a program that takes the root of a binary tree as input and checks whether the tree is height-balanced.
    A tree is height balanced if for each node in the tree, the difference in the height of its left and right subtrees is at most one.
    Approach 1 (Get Height Of Tree Rooted At Each Node)
    We can perform a traversal of the tree and at each node get the height of its left and right subtrees.
    This wastes time as we will be repeating work and the traversal of nodes.
    Approach 2 (Drill Down With Recursion And Respond Back Up)
    We can notice that we don't need to know the heights of all of the subtrees all at once.
    All we need to know is whether a subtree is height balanced or not and the height of the tree rooted at that node, not information about any of its descendants.
    Our base case is that a null node (we went past the leaves in our recursion) is height balanced and has a height of -1 since it is an empty tree.
    So the key is that we will drive towards our base case of the null leaf descendant and deduce and check heights on the way upwards.
    Key points of interest:
    1.) Is the subtree height balanced?
    2.) What is the height of the tree rooted at that node?
    Complexities
    Time: O( n )
    This is a postorder traversal (left right node) with possible early termination if any left subtree turns out unbalanced and an early result bubbles back up.
    At worst we will still touch all n nodes if we have no early termination.
    Space: O( h )
    Our call stack (from recursion) will only go as far deep as the height of the tree, so h (the height of the tree) is our space bound for the amount of call stack frames that we will create
    ++++++++++++++++++++++++++++++++++++++++++++++++++
    HackerRank: / @hackerrankofficial
    Tuschar Roy: / tusharroy2525
    GeeksForGeeks: / @geeksforgeeksvideos
    Jarvis Johnson: / vsympathyv
    Success In Tech: / @successintech
    ++++++++++++++++++++++++++++++++++++++++++++++++++
    This question is number 10.1 in "Elements of Programming Interviews" by Adnan Aziz, Tsung-Hsien Lee, and Amit Prakash.

ความคิดเห็น • 226

  • @BackToBackSWE
    @BackToBackSWE  5 ปีที่แล้ว +30

    Table of Contents:
    The Problem Introduction 0:00 - 0:33
    Cases That Are Height Balanced 0:33 - 1:56
    Cases That Are NOT Height Balanced 1:56 - 2:58
    Approach #1: Get Heights of Subtrees At Each Node 2:58 - 3:46
    Approach #2: Recurse To Base Cases 3:46 - 4:23
    Walkthrough of The Recursion 4:23 - 12:39
    Time Complexity 12:39 - 13:25
    Space Complexity 13:25 - 13:39
    Wrap Up 13:39 - 13:57
    The teacher's notes contain a link to the code for the problem discussed in the video. It is fully commented for teaching purposes strictly.

    • @dolcyrao5763
      @dolcyrao5763 4 ปีที่แล้ว +2

      You're really amazing, I was enjoying your teaching. Thanks a lot for this high-quality teaching for free.

    • @BackToBackSWE
      @BackToBackSWE  4 ปีที่แล้ว +1

      great to hear!!!

    • @anthonysummit3098
      @anthonysummit3098 3 ปีที่แล้ว +13

      Where is the code?

    • @sivaprakashkkumar9691
      @sivaprakashkkumar9691 3 ปีที่แล้ว +12

      Where is code

    • @debanjanasantra6724
      @debanjanasantra6724 3 ปีที่แล้ว +9

      Could not find the link to the code :(

  • @BismaSuleman
    @BismaSuleman 3 ปีที่แล้ว +78

    Me on Tinder: Hey, what is your height? And are you balanced?

    • @BackToBackSWE
      @BackToBackSWE  3 ปีที่แล้ว +5

      ye

    • @ExplorerSpace
      @ExplorerSpace 3 ปีที่แล้ว

      @@BackToBackSWE i am average height

    • @johnpaul4301
      @johnpaul4301 3 ปีที่แล้ว

      Balanced here might mean whether your tootsiroll matches your height

    • @WyMustIGo
      @WyMustIGo 2 ปีที่แล้ว

      @@johnpaul4301 th-cam.com/video/lbnoG2dsUk0/w-d-xo.html

  • @stephyjacob1256
    @stephyjacob1256 5 ปีที่แล้ว +70

    Sharing this channel to all my friends who are interested to learn data structure algorithm .. Please make more videos on Data Structure and algorithms .. Believe me nobody tech like you. This channel has potential to become one of the best. The difference between you and others, is that most people just jumps directly into the solution but you tell us 'the thought process', 'how to interpret the problem' which are most important. Your think loud approach is best part. Please don't stop making such video. People like me are always with you.

  • @rban123
    @rban123 4 ปีที่แล้ว +74

    Better than my data structures professor, thank you

  • @josephwong2832
    @josephwong2832 3 ปีที่แล้ว +3

    asking the "critical question" and then returning the answer to that question to my parent is a great way to reason about recursion in general
    your teaching style sir is on another level!!!

  • @adityajain-fn6ne
    @adityajain-fn6ne 4 ปีที่แล้ว +12

    You deserve way way more recognition and credit for the work you have done sir!
    better than any college professor I have had.

  • @nikhilkumarmishra1225
    @nikhilkumarmishra1225 5 ปีที่แล้ว +7

    OMG the way you explain the idea behind why the algorithm works, it just blew me away. Thanks a lot mate!

  • @turnuptheMIKEG
    @turnuptheMIKEG 4 ปีที่แล้ว +2

    you're a remarkable teacher. blew my PhD data structures professor out of the water, honestly. thank you for making these videos. I'm surviving interview season bc of this.

    • @BackToBackSWE
      @BackToBackSWE  4 ปีที่แล้ว +1

      lol nice, sure sure, they are a relic of the past self. I don't even remember recording some of these. Nice nice, you'll make it yo

  • @psthakur1199
    @psthakur1199 4 ปีที่แล้ว +5

    Loved that idea of "asking a question".Thanks man!!

  • @rakhman8621
    @rakhman8621 ปีที่แล้ว +2

    The way you explain everything man…the number of times you revisit some moments is perfect, the speed with which you explain the material is perfect. Keep up the good work and thank you for teaching us such important topics in such a great way.

  • @PherricOxide
    @PherricOxide 5 ปีที่แล้ว +4

    Thanks for the videos! They're very well done compared to most of the others where people either start writing code immediately or jump straight to the solution without explaining how they got there.

    • @BackToBackSWE
      @BackToBackSWE  5 ปีที่แล้ว

      Sure, this channel still has a long way to go

  • @afsinyilmaz8665
    @afsinyilmaz8665 3 ปีที่แล้ว +2

    great way of explaining stuff...Keep up the good work...you folks are as valuable as nation's best teachers.

  • @missrockinout
    @missrockinout 4 ปีที่แล้ว +10

    you get so into explaining this, gotta love the head scratch lmao
    thanks for an awesome explanation :D

  • @deepamkumar5211
    @deepamkumar5211 4 ปีที่แล้ว +3

    Your explanation is the best i have ever seen and really helps to understand these difficult problems. I appreciate your selfless work and the dedication with which you teach us these topics..Got to learn a lo from you,keep uploading more videos and soon this channel would turn out to be the best resource for interview preparation.

  • @MuhammadIrshadAli
    @MuhammadIrshadAli 4 ปีที่แล้ว +6

    Man, you should train CS professors at universities on how to teach algorithms

  • @johnmcway6120
    @johnmcway6120 4 ปีที่แล้ว +2

    Thank you very much. I myself teach myself to code, I'm also a teacher in kindergarten. I recognize a lot of myself in you. Keep up the good work!

  • @rahoolification
    @rahoolification 4 ปีที่แล้ว +1

    What you are doing is nothing short of humanitarian work my friend!

  • @adenosinetp10
    @adenosinetp10 3 ปีที่แล้ว +1

    why this has so less views??! No one these days teaches like this guy...not even my professor does....this video helped me creating a foundation for my data structure course

  • @priyogopalsingha3487
    @priyogopalsingha3487 2 ปีที่แล้ว

    undoubtedly, the best explanation of how recursion works in trees

  • @kunpeng8646
    @kunpeng8646 4 ปีที่แล้ว +2

    What a smart and attractive illustration, well-done man!

  • @wowzande
    @wowzande 5 ปีที่แล้ว +2

    That's gangsta as fuck we need more of this

  • @ruthylevi9804
    @ruthylevi9804 2 ปีที่แล้ว +1

    you are so gifted at teaching, never stop!

  • @MarshallThrottler
    @MarshallThrottler 3 ปีที่แล้ว +1

    I am so glad that I found your channel on TH-cam...! Thank You very Much Sir!

  • @nandanimadhukar
    @nandanimadhukar 4 ปีที่แล้ว +4

    Awesome explanation! Trees are speaking for themselves :D

  • @hugenerretho9151
    @hugenerretho9151 2 ปีที่แล้ว

    ur explanation is so concise that my golden retriever can now display his treats in tree structure

    • @BackToBackSWE
      @BackToBackSWE  2 ปีที่แล้ว

      Thank you, glad you liked it 😀
      Do check out backtobackswe.com/platform/content
      and please recommend us to your family and friends 😀

  • @Don_ron666
    @Don_ron666 5 ปีที่แล้ว +2

    Finally a clear cut video good job!

  • @quirkyquester
    @quirkyquester 4 ปีที่แล้ว +1

    Thank you man! This video really helps me to understand the process of solving the problem.

  • @amitmishra2736
    @amitmishra2736 4 ปีที่แล้ว +7

    Dude! I am not seeing the code in the down :(
    could you please update the Link

    • @BackToBackSWE
      @BackToBackSWE  4 ปีที่แล้ว

      The repository is deprecated - we only maintain backtobackswe.com now.

  • @wellingtonzane4288
    @wellingtonzane4288 5 ปีที่แล้ว +3

    Really detailed and clear explanation! Thank you!!!

  • @realmarciomarinho
    @realmarciomarinho 2 ปีที่แล้ว +2

    You said the code was below, but I cannot find it.

  • @SOURAVKUMAR-tw3ds
    @SOURAVKUMAR-tw3ds 3 ปีที่แล้ว

    awesome work bro!! helped a lot in visualization of recursion calls

  • @kevinandres3306
    @kevinandres3306 5 ปีที่แล้ว +2

    EXCELLENT explanation. extremely clear

  • @sankethb.k642
    @sankethb.k642 4 ปีที่แล้ว +1

    Thank you very much sir, your channel will soon be on the top.

  • @ShortGiant1
    @ShortGiant1 4 ปีที่แล้ว +2

    Great video, thanks. Appreciate the table of contents.

  • @max500k
    @max500k 3 ปีที่แล้ว +1

    Great job! You explained this well

  • @doruwyl
    @doruwyl 5 ปีที่แล้ว +1

    Very cool approach with the nodes which are "bellow sea level". 😊

  • @baraaabuasal5626
    @baraaabuasal5626 2 หลายเดือนก่อน

    at 6:00 I was like, say no more => Subscribed.
    fkn love the way explain stuff man

  • @TheAntloo
    @TheAntloo 4 ปีที่แล้ว +1

    Awesome walkthrough! Gave me a nice intuition on how I would write the code. Do you think you could make a video on how to insert a node into a BBST?

  • @ahiduzzamanahir1338
    @ahiduzzamanahir1338 2 ปีที่แล้ว

    WHAT! Did you just teach me recursion? I thought it was impossible!

  • @maripaz5650
    @maripaz5650 3 ปีที่แล้ว +2

    Best interview prep ever :)

  • @ramizrizwan3057
    @ramizrizwan3057 ปีที่แล้ว

    Such a good explanation, you’re the best!

    • @BackToBackSWE
      @BackToBackSWE  ปีที่แล้ว

      Happy Holidays! Really glad to help 🎉 Do you know about the BacktoBackSWE 5 Day Free Mini Course? Check it out here - backtobackswe.com/

  • @TacklessNebula3
    @TacklessNebula3 3 ปีที่แล้ว

    Made your 2K to 2.1K...
    Thanks for the brief explanation!

  • @neghatnazir1668
    @neghatnazir1668 4 ปีที่แล้ว +1

    awesome explination , i love the way you explain things.

  • @Jan_Jan_
    @Jan_Jan_ 4 หลายเดือนก่อน

    Amazing explanation, thank you! :)

  • @hinocenciopaulo
    @hinocenciopaulo 6 หลายเดือนก่อน

    Thank you so much for this beautiful explanation 🙏

  • @user-ej3iw8lw3w
    @user-ej3iw8lw3w 2 ปีที่แล้ว

    A balanced binary tree, also referred to as a height-balanced binary tree, is defined as a binary tree in which the height of the left and right subtree of any node differ by no more than 1.

  • @qingruxia6312
    @qingruxia6312 3 ปีที่แล้ว

    I love u your videos so much! Thank you so much for your time and work!

  • @aatifnazar1766
    @aatifnazar1766 4 ปีที่แล้ว +2

    The node which is marked red cross will not return 2. It breaks the call there only.

  • @eliasmoreno4672
    @eliasmoreno4672 4 ปีที่แล้ว +1

    you explained this so well. wow.
    *subscribed :)

  • @pushkalkatara2153
    @pushkalkatara2153 5 ปีที่แล้ว +1

    Hey, really a great explanation man! It'd be awesome if you could whiteboard the pseudocode too after the explanation.

  • @MahmoudSayed-hg8rb
    @MahmoudSayed-hg8rb 2 ปีที่แล้ว

    I'm kinda late idk if you'll respond to this comment
    first of all thanks for your efforts.
    second thing ... as far as I know ( and i almost know nothing yet, I'm just a beginner), something doesn't add up in the last example
    Dont we consider a tree a Balanced tree if the absolute difference of the heights of each side is

  • @neotong9885
    @neotong9885 5 ปีที่แล้ว +1

    really nice job on explaining Balanced Binary Tree!

  • @saikatdutta1991
    @saikatdutta1991 5 ปีที่แล้ว +1

    Hey bro, I want you to explain "Median in a stream of integers (running integers)" this problem. I am unable to understand why we need to use self balanced binary tree to solve this problem. Thanks. I will be helpful.. You explain better than any other.

    • @BackToBackSWE
      @BackToBackSWE  5 ปีที่แล้ว +1

      I'll be covering that in my class but not on the channel, most of my technical videos will go there now. I'm going to convert the channel into a more "I'm building things" type thing soon

  • @rhiannonsmeby9566
    @rhiannonsmeby9566 3 ปีที่แล้ว

    This video was fireeee I hate recursion but this visualization and explanation really helped

  • @malaguna66
    @malaguna66 4 ปีที่แล้ว

    This explanation is so clear so good!

  • @powerstrike97
    @powerstrike97 3 ปีที่แล้ว

    Nice explanation! Thank you!

  • @fantasy9960
    @fantasy9960 ปีที่แล้ว

    wow, your teaching is amazing! thanks again!

  • @yuyu-qr7ih
    @yuyu-qr7ih 4 ปีที่แล้ว +1

    very detailed explaination brada love u

  • @khan.mansoor
    @khan.mansoor 3 ปีที่แล้ว

    Great explanation! Do you have a link to the code for this problem that I can refer to?

  • @wahtthepho
    @wahtthepho 3 ปีที่แล้ว

    excellent explanation!! thank you!

  • @Kellworkie
    @Kellworkie 15 วันที่ผ่านมา

    Amazing teaching!

  • @shruthiranganatha7333
    @shruthiranganatha7333 4 ปีที่แล้ว +2

    Why add 1 to max(heightOfRightNode, heightOfLeftNode) ?, Wha's the logic here??

    • @BackToBackSWE
      @BackToBackSWE  4 ปีที่แล้ว +1

      Including the node that the call is working on in the height as the calls go up

  • @pewdiepieschair2693
    @pewdiepieschair2693 3 ปีที่แล้ว

    thanks lad, much appreciated!

  • @mohannadbayoumi9686
    @mohannadbayoumi9686 4 ปีที่แล้ว +1

    May I ask what the complexity of the non-efficient way you mentioned in the beginning of the video is?

  • @syedmdharris8814
    @syedmdharris8814 3 ปีที่แล้ว

    we can simply check whether each node has left and right node?
    can you explain about that

  • @randalllionelkharkrang4047
    @randalllionelkharkrang4047 3 ปีที่แล้ว +1

    if it has to fail, it will always fail at the root node right? can you provide with a counterexample to what I said?

  • @wappa6914
    @wappa6914 4 ปีที่แล้ว +1

    Thank you from France !

  • @techzoo1
    @techzoo1 4 ปีที่แล้ว +1

    Your explanation is somehow kinda funny (in a good way)!

    • @BackToBackSWE
      @BackToBackSWE  4 ปีที่แล้ว

      yeah I was weird when the channel started. no one was watching

  • @SreyesSrinivasan
    @SreyesSrinivasan 3 ปีที่แล้ว

    Great explanation, thanks a lot :)

  • @ashwanigupta4672
    @ashwanigupta4672 3 ปีที่แล้ว

    Finally got an awesome explanation 🏆

  • @ggzz8845
    @ggzz8845 3 ปีที่แล้ว +2

    where is the code ?

  • @user-zm5gs1sv2n
    @user-zm5gs1sv2n 4 ปีที่แล้ว +1

    thank you much ,I totally uderstand how recursion work

  • @AllNaturale11
    @AllNaturale11 ปีที่แล้ว

    very helpful. thank you!

    • @BackToBackSWE
      @BackToBackSWE  ปีที่แล้ว +1

      Thank you! Please enjoy a special code from us - backtobackswe.com/checkout?plan=lifetime-legacy&discount_code=AllNaturale11 🎉

  • @shijames4129
    @shijames4129 5 ปีที่แล้ว +2

    nice video!!! thanks!!

  • @ifelsedeveloper
    @ifelsedeveloper 4 ปีที่แล้ว

    hey! love your videos! one question, can't i just check the absolute height difference from each node? without asking are you balanced to each node?

    • @BackToBackSWE
      @BackToBackSWE  4 ปีที่แล้ว

      Yes but that will duplicate subtree measurements

  • @jgraiver
    @jgraiver 4 ปีที่แล้ว +1

    have you done the code for this anywhere?! loved the video

    • @BackToBackSWE
      @BackToBackSWE  4 ปีที่แล้ว

      I think so here: github.com/bephrem1/backtobackswe

  • @RedRabbitII
    @RedRabbitII 3 ปีที่แล้ว

    love this! thank you

  • @wentingzhang3097
    @wentingzhang3097 4 ปีที่แล้ว +2

    I'm having trouble finding the code in the description! :(

    • @BackToBackSWE
      @BackToBackSWE  4 ปีที่แล้ว

      The repository is deprecated - we only maintain backtobackswe.com now.

  • @maidul13
    @maidul13 4 ปีที่แล้ว +1

    I just don't get why its max(-1,-1)+1, is that supposed to be equivalent to taking absolute value? if so can you explain please

    • @BackToBackSWE
      @BackToBackSWE  4 ปีที่แล้ว

      I am just simulating the code as it would execute the base case.

  • @hikemalliday6007
    @hikemalliday6007 ปีที่แล้ว

    this dude kills it

  • @intoeleven
    @intoeleven 4 ปีที่แล้ว +1

    the time complexity is wrong, it should be O(n*log n), n is for getting height for each node and you need to check every node for balanced is log n.
    The worst case could be O(n^2) in this top-down solution, actually.

    • @BackToBackSWE
      @BackToBackSWE  4 ปีที่แล้ว

      If the tree is skewed height checking is O(n)

    • @intoeleven
      @intoeleven 4 ปีที่แล้ว

      @@BackToBackSWE Yes, and you not only check the height, but also check the balanced, which will cost O(log n). The total time complexity should be O(n log n) leetcode.com/problems/balanced-binary-tree/solution/

  • @zackyang123
    @zackyang123 4 ปีที่แล้ว +1

    That 8:40 zoom is gold hahahaha

  • @aatifnazar1766
    @aatifnazar1766 4 ปีที่แล้ว +1

    A big thank you for this content

  • @mpalanipsbb
    @mpalanipsbb 7 หลายเดือนก่อน

    Best explanation!

  • @pawanacharya997
    @pawanacharya997 4 ปีที่แล้ว +1

    How can someone explain this clearly wow you really helped me..
    thanks

  • @MoscleBrog
    @MoscleBrog 7 หลายเดือนก่อน

    people like u save students like us😃

  • @kimmyliu5509
    @kimmyliu5509 2 ปีที่แล้ว

    May I ask where is the code? you mentioned it is in description but it is not...

    • @BackToBackSWE
      @BackToBackSWE  2 ปีที่แล้ว

      Do check out backtobackswe.com/platform/content

  • @shashankshekhar390
    @shashankshekhar390 4 ปีที่แล้ว +1

    That helped, thanks.

  • @poojaguru2516
    @poojaguru2516 5 ปีที่แล้ว +1

    Lifesaver : ) Thank you so much!! Best explanation ever!!

  • @stargazer8718
    @stargazer8718 ปีที่แล้ว

    What's the difference between this and an AVL tree?

  • @researchandbuild1751
    @researchandbuild1751 4 ปีที่แล้ว +1

    Could you just do a breadth search and if the count of children at a level count is odd, it is not balanced?

    • @BackToBackSWE
      @BackToBackSWE  4 ปีที่แล้ว

      How would this work exactly?

    • @researchandbuild1751
      @researchandbuild1751 4 ปีที่แล้ว

      @@BackToBackSWE well it seemed like possibly a feature of an unbalanced binary tree is it would have a level with non-even count of nodes. Unless i am misunderstanding what a balanced tree should look like (which is possible). So you just make a queue and walk down the nodes, pushing children at each. If your total count of children in the queue is ever odd at each step then you know the tree is unbalanced. Not sure if that would work or not though, just pondering

  • @ashishbisht980
    @ashishbisht980 4 ปีที่แล้ว +1

    Bro you are awesome , love from India

  • @salwaabdullah2003
    @salwaabdullah2003 4 ปีที่แล้ว +2

    Thanks 🙏

  • @XLpacman805
    @XLpacman805 2 ปีที่แล้ว +1

    Thanks

  • @nishanth998
    @nishanth998 4 ปีที่แล้ว +1

    where can i find the code in the website??plz tell me

    • @BackToBackSWE
      @BackToBackSWE  4 ปีที่แล้ว

      The repository is deprecated - we only maintain backtobackswe.com now.

  • @jf7462
    @jf7462 4 ปีที่แล้ว +1

    Bro, Can you tell me where the code is?

    • @BackToBackSWE
      @BackToBackSWE  4 ปีที่แล้ว

      We only maintain solutions on backtobackswe.com (paywall)

  • @darshantsdarshan1
    @darshantsdarshan1 4 ปีที่แล้ว +1

    This guy is awesome 👏

  • @zooomba62
    @zooomba62 ปีที่แล้ว

    great work brother

  • @abhishekk.3977
    @abhishekk.3977 3 ปีที่แล้ว +1

    Ok, I accept that I agreed to max(0,0) = 1. @ 8:40

  • @sameerpatel3476
    @sameerpatel3476 3 ปีที่แล้ว

    Would a tree be considered balanced tree if the root have only one node at one side ?