L32. Count total Nodes in a COMPLETE Binary Tree | O(Log^2 N) Approach | C++ | Java

แชร์
ฝัง
  • เผยแพร่เมื่อ 27 พ.ย. 2024

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

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

    Please likeeee, shareeee and subscribeeeeeeee :) Also follow me at Insta: Striver_79

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

      Why is it return (1

    • @g.upenderreddy
      @g.upenderreddy ปีที่แล้ว

      @@bhaveshkumar6842 If you observe carefully there's change in height calculation root vs root.left or root.right
      public int countNodes(TreeNode root) {
      if (root == null) return 0;
      int leftHeight = leftHeight(root);
      int rightHeight = rightHeight(root);
      if (leftHeight == rightHeight) return (1

    • @_PRANAYMATE
      @_PRANAYMATE 8 หลายเดือนก่อน

      @@g.upenderreddy You are right

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

    This question was asked today in DUNZO round-1 and interviewer was expecting this approach

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

    Self Notes:
    🍇 Formula is (2^TreeLevel - 1). Only works for perfect tree.
    🍇 To determine if its a perfect tree, go all the way down and count the nodes on left and right side, If they match, its a perfect tree and our formula applies.
    🍇 If its not a perfect tree, we go on left and right subtree and again determine if they are perfect tree.
    🍇 When we have our left and right heights, we do (1 + left + right)
    🍇 If we reach null, return 0
    🍇 C++ note: 1

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

    Instead of using two function to find left height first and then right height. We can use a single while loop and iterate till both of the root are not NULL and increment h++. if both are NULL then make the bool full=true and break and if anyone of them is NULL then just break. if full is true then return 2^h-1 else return 1+left+right
    int countNodes(TreeNode* root) {
    if(root==NULL)return 0;
    TreeNode* node=root->left;
    TreeNode* node2=root->right;
    int h=1;
    bool full=false;
    while(1){
    if(node==NULL && node2==NULL){
    full=true;break;
    }
    if(node==NULL || node2==NULL){
    break;
    }
    node=node->left,node2=node2->right;
    h++;
    }
    if(full){
    return pow(2,h)-1;
    }
    else{
    return 1+countNodes(root->left)+countNodes(root->right);
    }
    }

    • @mrmani1700
      @mrmani1700 6 วันที่ผ่านมา +1

      Nice man❤

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

    I went on to like this video when Striver asked for it at the end but found out that I already liked it (this is the first time I am watching this video). This is magic for Striver!!!

  • @rudrasharma8523
    @rudrasharma8523 17 วันที่ผ่านมา

    This can also be a solution with
    Time Complexity: The time complexity of this solution is O(n), where n is the number of nodes in the tree. This is because the function visits each node exactly once to count it, resulting in a linear traversal of the tree.
    Space Complexity: The space complexity is O(h), where h is the height of the tree. This is due to the recursive call stack that is used during the traversal. In the worst case, for a skewed tree (like a linked list), the height can be n, leading to O(n) space. In a balanced tree, the height would be log(n), resulting in O(log n) space.
    class Solution {
    public:
    int countNodes(TreeNode* root) {
    if(root==nullptr) return 0;

    int left = countNodes(root->left);
    int right = countNodes(root->right);
    return left + right + 1;
    }
    };

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

    Rather than finding height at every node we can pass left height and right height and in left recursion left height is equal to left height -1 and give call for right height and in right subtree right height is right height -1 and give call for left height only.

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

    My intuition before watching this video is normal traversing the tree from like BFS and while traversing take the count variable and increase the count by 1 if any node occurs while traversing the tree and then return count

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

    Thank you so much Striver for your amazing content. You have helped me understand the concepts which I initially used to find too intimidating.

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

    If anyone struck here , see this (2

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

    Correction: While returning the number of nodes, in the video's solution we are returning (1

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

      true

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

      You are wrong. You didn't understood code correctly because in code , he has already included root node in height

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

      or you could just start with hght=1 in both left and right height traversals then the formula will not change

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

    Leetcode discussion section se pareshaan hoke aaya and you satisfied bro.. thank youuuuuu

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

    This can also be done by binary searching on all the sizes possible. We have to check whether the size element is present in the tree or not. The complexity will be the same.

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

      This can also be done by applying binary search in the last level. Getting to the last level will take logN time and binary Search itself will take logN time, so overall logN_wholeSquare time

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

      checking whether the size element is present or not takes O(n) time for binary tree right?

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

    Just a correction to striver bhaiya's java code
    class Solution {
    public int countNodes(TreeNode root) {
    if(root==null)
    return 0;
    int left=ghl(root.left);
    int right=ghr(root.right);
    if(left==right) return (2

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

    Thank You So Much for this wonderful video...........🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻

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

    Very good explanation. I specially loved the explanation of Time complexity for this. I think no one clears TC in their videos apart from striver. so this clearing Time space complexities and clear explanation of solution gives him edge and makes him better than anyone teaching DSA

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

      It's uplifting to see children learn DSA at such a young age...

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

    Self note:
    why complexity is log2n,
    except for the last level every level needs to be compelty filled, so in the left side we might have to go till the last level finding a node whose left height and right height are similar which can be at max till approx logn level since complete is full execpt the last level ,and in every of those logn levels we came we must have computed height each of logn (since complete tree is filled execpt the last level) ->ogn*logn

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

      didn't understand why complexity is log2n

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

    IN cpp code
    if (left height == right height)
    we need to
    (1

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

      why is that needed ? 1

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

      @@shashamnk2525 that's how you calculate using bits
      1 is represented as
      00000000.......01
      In binary
      31 zeros then 1

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

      @@shivangmathur6112 I think we are calculating 2^h+1 because we are taking height of root as 0

  • @naveenkumarjadi2915
    @naveenkumarjadi2915 9 หลายเดือนก่อน

    Great Explanation bro , thank you for this series

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

    One LIne Brute Force (Recursive) : 0(n)
    int countNodes(TreeNode root)
    {
    return (root == null)? 0 : 1 + countNodes(root.left) + countNodes(root.right);
    }

  • @andr3w321
    @andr3w321 14 วันที่ผ่านมา

    I don't think the Time complexity analysis is correct for worst case runtime, but correct for average which was not explained.
    In best case: we're given a complete tree and traverse left and right side and return. O(2 * log N) ~ O(log N)
    In worse case: we're given a tree with all levels filled except last level only has one node. While we save some iterations on the right side, we are making repeated calls on the left side which more than makes up for it and worst case it degenerates to O(N).
    On average: Tree height: O(log N)
    Expected recursive calls: O(log N)
    Multiplicative: O((log N)^2)
    Time Complexity Summary:
    Best Case: O(log N)
    Worst Case: O(N)
    Average Case: O((log N)^2)

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

    Thank you so much for (logn*logn) approach.

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

    📝Slightly different approach by not calculating the same nodes repeatedly for calculating the height.....We check the binary tree is faulty or not..By faulty I mean not prefect.If the tree rooted at root is faulty,then check its left and right sub trees .Any one of them will be faulty.The other will be the reverse.We can exploit this binary possibility in this way.If the left child tree is faulty,then dont recurse to the right side tree ,because the rght side tree is perfect and thus add the no of nodes acc. to the formula to the count passed as reference.If the left child tree is not faulty,i.e perfect then sum the nodes and recurse to the right child tree.This process goes on recursively .In this way,we leave many perfect subtrees and calculate the number of nodes without visiting them.And then we hit the base case where the tree is like / or . ...Then we return from there.We are not calculating repeatedly the heights again and again thus not repeteadly travelling the same nodes for finding the height...for the child trees the height will be that of parent-1 .for left child tree the left ht will be left ht of parent-1 and right ht we have to find....thus ensuring we are travelling the nodes only once ,not repeteadly.This further brings down the time.The complexity is O((logn)^2).
    class Solution {
    public:
    bool helper(TreeNode* root,int lh,int rh,int& count){
    if(lh==rh) {
    count+=(1left;
    }
    helper(root->right,lhr,rh-1,count);
    count+=1;
    }
    return false;
    }
    int countNodes(TreeNode* root) {
    int lh=0,rh=0;
    TreeNode* node=root;
    while(node){
    lh++;
    node=node->left;
    }
    node=root;
    while(node){
    rh++;
    node=node->right;
    }
    int count=0;
    helper(root,lh,rh,count);
    return count;
    }
    };

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

    Python code:
    class Solution:
    def countNodes(self, root: Optional[TreeNode]) -> int:
    def rightheight(root):
    h=0
    while root:
    h+=1
    root=root.right
    return h
    def leftheight(root):
    h=0
    while root:
    h+=1
    root=root.left
    return h
    if leftheight(root)==rightheight(root):
    h=leftheight(root)
    return (2**h)-1
    else:
    return 1+self.countNodes(root.left)+self.countNodes(root.right)

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

    loved the thought process. Dry running it multiple really helped me grasp the concept. Good question using the properties of a specific type of tree.

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

    Nice explanation your videos are really good...please keep on making such videos...you are doing a great job.

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

    Understood 👍 Time complexity explanation is really good

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

    Loved the video. You are the best! Keep going...

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

    thank you sir great explanation.

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

    Awesome Explanation. Leetcode solution was intimidating.

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

    Great explanation & crisp code just what striver do
    Great explanation & crisp code just what striver do

  • @adebisisheriff159
    @adebisisheriff159 10 หลายเดือนก่อน

    Thanks Striver

  • @sharmanihal99
    @sharmanihal99 5 หลายเดือนก่อน

    Python Code for the same:
    class Solution:
    def countNodes(self, root: Optional[TreeNode]) -> int:
    if not root:return 0
    left_depth=self.find_left_branch_depth(root)
    right_depth=self.find_right_branch_depth(root)
    if left_depth==right_depth:
    return (2**left_depth)-1
    else:
    return 1+self.countNodes(root.left)+self.countNodes(root.right)
    def find_left_branch_depth(self, root):
    if not root:return 0
    return self.find_left_branch_depth(root.left) + 1
    def find_right_branch_depth(self, root):
    if not root:return 0
    return self.find_right_branch_depth(root.right) + 1

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

    class Solution {
    public int countNodes(TreeNode root) {
    if(root == null) return 0;
    return countNodes(root.left) + countNodes(root.right) + 1;
    }
    }
    Java code beats 100%

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

    DOUBT : In C++ code why do we write (1

  • @DeadPoolx1712
    @DeadPoolx1712 25 วันที่ผ่านมา

    UNDERSTOOD;

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

    Loved it solved on my own

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

    This nice intuition really liked it.

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

    Mauj kardi bhai ne.. 🔥🔥

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

    Bhaiya, there is a typo in the java code, the while loop will have to execute till root != null but, in the code there was root.left and root.right in the two functions(We can also set the count initial value to 1, that will also work).
    At 13:17 , I got a bit confused on the part when you were explaining the calculation of the left height and the right height. I thought that the code won't work for the test case :
    1
    / \
    2 3
    / \ / \
    4 5 6 7
    / \ /
    8 9 10
    But then I dry ran the code and got to know that what you are actually doing is finding the depths of the rightmost and leftmost nodes of a given root. And then if you find that the depths are equal, we can thereby conclude that for the given root, the leftmost and the rightmost nodes are at the same level, and thus, by the definition of complete binary trees, we can further conclude that the tree is completely filled the complete binary tree.
    So, for the test case I mentioned above, for node 2, the depth of leftmost node (8) != the depth of rightmost node(5). So it will go on and check for the individual deeper nodes. Thus, the code will work fine.

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

      concluded well :)

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

      @@kaushikramabhotla4635 Thanks 😊

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

      thanks clearing my doubt

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

      what if the tree is like this:
      2
      / \
      3 4
      / \ / \
      3 5 9 10
      /
      6
      then for left subtree of 2's height will be 3 and for right subtree of 2 it will also be 3 then it will calculate the nodes with the help of that formula which will give wrong result since it missed the last node (6).

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

      @@ishantrivedi5588 this is not a complete binary tree according to question given questions is always a complete binary tree

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

    Great approach bhaiya maza aa gaya

  • @Learnprogramming-q7f
    @Learnprogramming-q7f 8 หลายเดือนก่อน

    Thank you Bhaiya

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

    just a correction to bhaiya's cpp code:
    class Solution {
    private:
    int findHeightLeft(TreeNode* node){
    int hgt=0;
    while(node){
    hgt++;
    node=node->left;
    }
    return hgt;
    }

    int findHeightRight(TreeNode* node){
    int hgt=0;
    while(node){
    hgt++;
    node=node->right;
    }
    return hgt;
    }
    public:
    int countNodes(TreeNode* root) {
    if(!root)return NULL;
    int lh=findHeightLeft(root->left);
    int rh=findHeightRight(root->right);
    if(lh==rh)return (1right);
    }
    };

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

      bro you're a savior
      been trying figure out for so long what was wrong with the code
      thanxxxxxx

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

    Understood! So fantastic explanation as always, thank you very much!!

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

    Great explanation & crisp code just what striver do

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

    Understood

  • @abhijit-sarkar
    @abhijit-sarkar ปีที่แล้ว

    Time Complexity discussion at 13:40. You're welcome.

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

    we love your content and we love you...🖤

  • @AdityaKumar-be7hx
    @AdityaKumar-be7hx ปีที่แล้ว

    Buddy, you are amazing!

  • @someshpatel7660
    @someshpatel7660 3 หลายเดือนก่อน +1

    !!! IMP PLEASE REMEMBER :
    Here height of subtree is not exactly the subtree height, but here height (height term is bit confusing) calculation is the way to find out which subtree is perfect. i.e If the left boundary edges == right boundary edges.
    Dont confuse it with height

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

    Thank you

  • @chiragbansod8252
    @chiragbansod8252 8 หลายเดือนก่อน

    UNDERSTOOD

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

    Thank you sir

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

    Thanks brother!

  • @ASHISHKUMAR-jh9kw
    @ASHISHKUMAR-jh9kw 2 ปีที่แล้ว +1

    In JAVA code there should be ((1

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

    Striver is Literally God for DSA.

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

    understood,awesome striver

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

    Love you bhai

  • @jk-sm6qr
    @jk-sm6qr 8 หลายเดือนก่อน

    thanks

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

    Great Great Explanation..Thank you

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

    great explanation as expected..thanks a lot for ur efforts

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

    What a explanation...🙇‍♀️thanks a lot😅👍

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

    completed lecture 32 of free ka tree series.

  • @raviraj-xq4ue
    @raviraj-xq4ue 2 ปีที่แล้ว

    bhai aise algo sochte kaise ho yaar ???
    mtlb ki gazab

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

    Amazing video!

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

    i think the logic is somewhat broken as if in the first example there is left child of 6 then then lh=rh=4 would have held true....and we would have returned 2^4-1=15 but the ans is 12

  • @harshitjaiswal9439
    @harshitjaiswal9439 9 หลายเดือนก่อน

    understood

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

    you are superb sir

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

    Great sirr

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

    Greatt explanation....🙏🙏

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

    Hi,
    Considering the subtrees of Node 2, if we remove the Node 11 from the right sub-tree, The height would still be 3. Am I getting it wrong?

    • @subhasishkumbhakar1028
      @subhasishkumbhakar1028 11 หลายเดือนก่อน

      NO, you are wrong. If we remove 11, it will not be same.

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

    Can we say that since this is an Almost Complete Binary Tree, which means the condition (leftHeight==rightHeight) will satisfy at-least once & not go wasted ?

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

      yeah . thats why we wont be traversing either the right or the left subtree once we find the height diference. one of the part has to satisfy this condition.

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

    Huge Respect...❤👏

  • @TarunKumar-cn6in
    @TarunKumar-cn6in 3 ปีที่แล้ว

    Thanks so much sir🙏

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

    thanks mate!

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

    good algo

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

    understood!!!!!!!!!!!!!

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

    understood

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

    got it sir thanks a lot

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

    i think in c++ code , it should be if(lh==rh) return (1

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

    your code is wrong and leetcode test cases are incomplete:
    why?
    because consider this test case
    [1,2,3,4,NULL,6,7]

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

    practically, this method was .07 ms faster than the O(n) solution. Yeah nice.

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

    thanks

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

    Understood!!

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

    Why is it return (1

    • @AB-iv4bq
      @AB-iv4bq 2 หลายเดือนก่อน

      can also use pow(2,lh) in c++

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

    Understood:)

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

    I could not understand how the TC Is O(logn^2) for the worst-case. even if we apply the formula, for calculating the left and right height we are traversing through all the nodes for the right part. Someone pls help me.

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

      Complete binary tree height is always log n.

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

    Bhai Graphs ke bad Ek video Bit manipulation ke bareme banao na...

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

    should be 1

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

    Understood

  • @yuvrajkumar3765
    @yuvrajkumar3765 5 หลายเดือนก่อน +1

    Guyz we are finding left most height and right most height we are not finding general left height and right height

  • @AmanKumar-dh8md
    @AmanKumar-dh8md 2 ปีที่แล้ว +6

    Doesn't this traverse all the nodes while calculating height?

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

      Nope. While finding height we just keep on going on one side. If we're finding left height we just keep on going left till we find a NULL and we don't move to right.

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

    what if 5 has only one node
    the height will be the same but the formula won't work right?

  • @ravipatel-xu5qi
    @ravipatel-xu5qi 10 หลายเดือนก่อน +1

    we are traversing each node to get the heights of left or right part. So all N nodes are traversed. Even in normal pre order or post order traversal also we can count this number of nodes. Why to go for this approach.

    • @spicy46475
      @spicy46475 5 หลายเดือนก่อน

      becaus it has less time complexity

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

    I have a small query in java code.
    when you call the getHeightRight or getHeightLeft Function
    why do you write
    while(root. left!=null) --It does not give actual height of the left side
    why not like this
    while(root!=null) -- it gives correct height
    //your code is working fine.
    //above query ate my head.

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

    I have a doubt that bhaiya wrote if (left != right) --> this mean that the tree is not complete but in the question it is given that the tree is complete??

  • @fazilshafi8083
    @fazilshafi8083 3 หลายเดือนก่อน

    JAVA SOLUTION ⏬
    class Solution {
    private int calculateLeftHeight(TreeNode node){
    if(node == null){
    return 0;
    }
    int count = 0;
    while(node.left!=null){
    count++;
    node = node.left;
    }
    return count;
    }
    private int calculateRightHeight(TreeNode node){
    if(node == null){
    return 0;
    }
    int count = 0;
    while(node.right!=null){
    count++;
    node = node.right;
    }
    return count;
    }
    public int countNodes(TreeNode root) {
    if(root==null){
    return 0;
    }
    int leftH = calculateLeftHeight(root);
    int rightH = calculateRightHeight(root);
    if (leftH == rightH) {
    return (2

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

    can anyone tell what is exact meaning of the height of a tree?
    What i have know that the height is the longest path where no of EDGES are from a particular node to any leaf node.
    But according to this video,he represented height with no.of NODES not EDGES

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

      Actually, you can think both the way it never matters.

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

      It depends on what is required in the question. Generally it should be the number of levels i.e. number of nodes, however you may be asked/need to calculate number of edges in some questions

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

    💚

  • @deepaksingh-qd7xm
    @deepaksingh-qd7xm 7 หลายเดือนก่อน +1

    ok my question is if we are traversing the complete tree to find the height of tree why not count the nodes in same only its the same thing ???????????????????????? 🙄🙄🙄🙄🙄🙄🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔