L29. Children Sum Property in Binary Tree | O(N) Approach | C++ | Java

Поделиться
HTML-код
  • Опубликовано: 25 янв 2025

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

  • @takeUforward
    @takeUforward  3 года назад +92

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

    • @yashdubeyofficial
      @yashdubeyofficial 3 года назад

      bhaiya what will happen if the root node is 2 and rest of the childrens are higher than 2 just like in 1 question of the video

    • @AyushYadav-lz5zc
      @AyushYadav-lz5zc 3 года назад +2

      @@yashdubeyofficial so we have to change the value of root by the sum of the left and right child

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

      In line 16 of both the codes it will only be if not else if

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

      GOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAT

    • @roshangeorge97
      @roshangeorge97 7 месяцев назад

      okkkkkkkkkkkkkkkkkkkkkkkkkk:)

  • @mayankbharti531
    @mayankbharti531 Год назад +47

    For the people who are saying that in line 16 it should be "if" instead of "else if", actually "else if" is fine because in this condition any one of the children in left and right will be made equal to the root->val so it will eventually serve the purpose, as the sum will now automatically be bigger than the root->val as one of the child is equal to root->val.

    • @22gauravkumar70
      @22gauravkumar70 Год назад +5

      will not work if negative value exists

    • @harshits-1195
      @harshits-1195 Год назад +2

      i have a doubt in this because when if condition is satisfied why it will go to else if statement

  • @uRamPlus
    @uRamPlus 3 года назад +264

    Self Notes 📜:
    🥥 if both children sum is less than parent, make children's value to parent's value.
    🥥 if both children values sum is greater than or equal to parent, make parent's value to children's sum.
    🥥 recursively go left and right. Traversal type: DFS.
    🥥 when coming back up the tree, take children sum and replace it in parent.
    🥥 at any point we reach null, just return (base case)
    🥥 Intuition: while going down, increase the children values so we make sure to never fall short, then all we have to do is sum both children and replace it in parent.

    • @auroshisray9140
      @auroshisray9140 3 года назад +7

      Thank you!!

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

      hey i have a doubt, anyone can pls reply to it.
      pt-2 - if both children values sum is greater than or equal to parent, make parent's value to children's sum.
      so here when why we make this.
      As anyways while returning back to sum, we will simply do sum and replace parent, so why this step??
      PLEASE TELL

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

      @@balakrishnanr648 I have same doubt , I submitted on codestudio without this condition and my soln was accepted .

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

      @@balakrishnanr648 there may be a chance that you get higher value in parent than the total sum value of its both child to avoid this we have to continuously increase the childs value because we can't decrease the value we can only increase the value

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

      @@balakrishnanr648 You are correct....that step is not required.....anyways it will change the value of root after returning..no need to change it beforehand.....

  • @JustForFun-zz2hb
    @JustForFun-zz2hb Год назад +20

    An important optimization:
    We don't need to consider the case where child>=root->data.
    We only need to consider the case where childdata and increase the value of child to root->data.
    The optimized code:
    void changeTree(BinaryTreeNode < int > * root) {
    if(root==NULL)
    return;
    int child=0;

    if(root->left)
    child+=root->left->data;
    if(root->right)
    child+=root->right->data;
    //we make sure that while going down the child has no shortage
    if(child < root->data)
    {
    if(root->left)
    {
    root->left->data=root->data;
    }
    if(root->right)
    {
    root->right->data=root->data;
    }
    }
    changeTree(root->left);
    changeTree(root->right);
    //while going back up
    int tot=0;
    if(root->left)
    tot+=root->left->data;
    if(root->right)
    tot+=root->right->data;

    if(root->left || root->right)
    root->data=tot;
    }

  • @sakshisinghal1669
    @sakshisinghal1669 2 года назад +161

    Line 19 and 20 in C++ code should be calling the same function so it should be changeTree instead of reorder

  • @course_adda1597
    @course_adda1597 3 года назад +25

    Genious. I have implemented it in O(n^2) but never thought it could be done in O(n). Thanks a lot

  • @Saiviswateja
    @Saiviswateja 2 года назад +21

    Thanks, Striver for the explanation you are making our lives very easy with your hard work.
    I think that else in 16 line is not required just if is enough

    • @VishalGupta-xw2rp
      @VishalGupta-xw2rp 2 года назад +4

      Haina.... Cause if child value is less then we are updating the values of *both* the children if they are *present* to root value.
      Thanx for the confirmation.
      Striver your existence itself is a blessing man ♥️🔥

    • @parthsalat
      @parthsalat 2 года назад +4

      You're right.
      But think about why we are updating child nodes. We are doing it, so that SUM of child nodes becomes greater than or equal to the parent node.
      Now if you update both children to parent's value (say x), while returning from function call, parent would be updated to SUM of child nodes, right? Means, 2x.
      However, if like striver, you use if and else, only one of the node will have the value x. The other will be having a value smaller than x. Their SUM will be < 2x.
      This will help *prevent integer overflow*

    • @skyFullOfStars
      @skyFullOfStars 2 года назад +4

      even line #13 is not needed na?
      why update root = left+right while traversing down the tree?
      anyway this operation will happen when we're coming back up.
      right?

  • @bhaveshkumar6842
    @bhaveshkumar6842 2 года назад +5

    Greatest DSA content by a big margin!!

  • @SHASHANKRUSTAGII
    @SHASHANKRUSTAGII 3 года назад +69

    Before knowing O(n), you should tell the students Brute force then O(N^2) and then teach O(N)

    • @codetrooper9279
      @codetrooper9279 Год назад +4

      Don't be bothered

    • @ciaassasian
      @ciaassasian 10 месяцев назад +2

      ayo rustagi bhaiya how're you?
      your twitter follower here!

    • @pratyush2331raj
      @pratyush2331raj 10 месяцев назад +1

      I was also going to comment the same

    • @Ashborn-g1r
      @Ashborn-g1r 3 месяца назад

      Weakling spotted

  • @shivamgoel2766
    @shivamgoel2766 3 года назад +70

    In line 14 inside the else block, in the explanation, you were saying that assigns the value of root node to both the children but in the code, the root value is being assigned to either left or right child. According to explanation it should be like,
    if(root->left)
    root->left->data=root->data;
    if(root->right)
    root->right->data=root->data;

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

      i think its just a mistake.

    • @NikhilSharma-mv8hq
      @NikhilSharma-mv8hq 2 года назад

      yeah right buddy

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

      Yeah may be silly mistake in the code

    • @sarthakbhatia7888
      @sarthakbhatia7888 2 года назад +9

      @@krishnavamsichinnapareddy It's not a mistake. Think about it all we need is that root node should not be greater than the sum of it's children. Even if we make any one equal to root node our problem will be solved.

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

      Its not required to even make it equal to the root value....we can just get the difference of both and add that difference to any one of the node....and it will make sure that the sum of both the child is equal to root value....

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

    what would be the approach is the qs is-
    1. Convert to childrenSum, with minimum no. of nodes changed
    2. Convert to childrenSum, with minimum value added to all nodes cumulatively.

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

    I have developed a method by myself. Make root->data as INT_MAX. Their children should be INT_MAX/2 and so on. if one of children greater than INT_MAX/2 just make the other child as parent->data-child1->data. Now recurse. This works because the cases take care of the fact that the sum of the children never goes beyond INT_MAX for all levels.

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

      Sounds great. Do you have the code?

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

      ya it's nice approach , but while backtracking pls also update nodes , because diving by 2 can lead to zero in some edge cases , due to which might summation at top node will differ

  • @rishabkumar4940
    @rishabkumar4940 3 года назад +71

    What if I first check the maximum element in the whole tree, then assign that value to every leaf node and sum them to their parents. That will also solve the question in linear time

    • @takeUforward
      @takeUforward  3 года назад +22

      Yes does that.

    • @srishtigupta9516
      @srishtigupta9516 2 года назад +10

      Yes that can be done, but it has a higher chance of resulting in overflow for large values.

    • @Rajesh-op8zx
      @Rajesh-op8zx 2 года назад +5

      @@srishtigupta9516 plus finding maximum element itself requires 1 more travesal

    • @shikharsharma3980
      @shikharsharma3980 2 года назад +4

      @@Rajesh-op8zx Not necessarily, instead of finding maximum element overall, you can just find the maximum value encountered till now, pass by reference, and keep updating, this way you don't need any additional traversal.
      a leaf node can have any value provided it is greater than all its ancestors. then we can fix the parents as equal to sum of children.

    • @sidharthgupta5-yeariddbioc651
      @sidharthgupta5-yeariddbioc651 2 года назад +2

      @@shikharsharma3980 I think videos approach is little complex but finding max then go ahead is little easy What you think about that bro .

  • @amanverma9829
    @amanverma9829 3 года назад +51

    int fun(BinaryTreeNode < int > * root,int par)
    {
    if(!root)
    return 0;
    int l=fun(root->left,max(root->data,par));
    int r=fun(root->right,max(root->data,par));
    root->data=max(l+r,max(root->data,par));
    return root->data;
    }
    void changeTree(BinaryTreeNode < int > * root) {
    fun(root,0);
    }

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

      Nice Aman bro

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

      didn't get it, why u used par?

    • @your_name96
      @your_name96 2 года назад +5

      @@abhishekseth5852 keeping track of the parent node's value, he eliminated the lines 5-17 evaluation using that, but in interview it become more difficult to explain this kind of code.

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

      @@your_name96 but it is very clean following the approach.

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

      @@your_name96 can u provide the ques link?????

  • @adityapundir5549
    @adityapundir5549 3 года назад +41

    In line 14 inside the else block, in the explanation you were saying that assign the value of root node to both the children but in the code the root value is being assign to either left or right child. I am really confused why is it so, according to explanation it should be like,
    if(root->left)
    root->left->data=root->data;
    if(root->right)
    root->right->data=root->data;

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

      yes man, You are right

    • @rishabhkumar8115
      @rishabhkumar8115 3 года назад

      yes i think its typo

    • @Mayanksingh-qp6dy
      @Mayanksingh-qp6dy 3 года назад

      Yeah

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

      The code shown in the video is also correct, our main goal is to make sure that we do not need to subtract anything from the root. Increasing any one of the child nodes to the root value will do the job

    • @kickmegreen1299
      @kickmegreen1299 3 года назад +5

      @@shikhar2k01 no,if root->right is -ve ,their addition will be less than root->data.

  • @sujan_kumar_mitra
    @sujan_kumar_mitra 3 года назад +5

    Understood.
    BTW, i feel like the problem title should be "Convert binary tree to children sum tree"

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

    Understood..........Simply Amazing ... loved the approach. You are generous.

  • @thatowlfromhogwarts490
    @thatowlfromhogwarts490 2 года назад +4

    i thought of a different approach! like find the maximum value in the tree, keep assigning and incrementing that value increasing order bottom to up, makes it in O(N) and pretty straight forward ig! but it will need 2 traversals to get it done...

    • @i-am-darshil
      @i-am-darshil Год назад +1

      I like this approach. Thanks for posting 🙌🏻

  • @pratyushbhatt1712
    @pratyushbhatt1712 3 года назад +8

    Typo in line 19 and 20 of CPP code

  • @Area-fd8ht
    @Area-fd8ht Год назад +3

    Striver bhai pk ho kya yr aap..
    Line 19 or 20 me reorder call kar diya mtlb kuch bhi ho rha hai..
    Wese explain bhut mst kiya tha love you..❣️

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

    excellent approach. just blew my mind away. How to do this question if we needed sum to be as minimized as possible?

  • @urvashidang6610
    @urvashidang6610 2 года назад +4

    Bhaiya ek minor mistake h code m reorder(root->left) ki jgh changeTree() ayega. Happy Learning. Thankyou for amazing content.

  • @krishnavamsichinnapareddy
    @krishnavamsichinnapareddy 2 года назад +6

    I think line 13 is not required. We can just check for child < root->data.
    Why line 13 is not required because after completing left and right recursion we will be adding left and right children values and update that value to root. Am I correct ?

  • @umeshkaushik710
    @umeshkaushik710 9 месяцев назад +4

    Not able to find the exact same question on any coding platform, Anyone help plz

  • @moviesflix7082
    @moviesflix7082 6 месяцев назад +3

    Which Platform does have this question?

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

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

  • @harshmittal3128
    @harshmittal3128 2 года назад +8

    The case when the sum of left and right child is greater than the parent node, there is no need to update the parent node , because the value of nodes can only be increased or remain constant and in either of the cases the parent node's value would for sure be lesser than the sum of children.
    Correct me if I'm wrong, and also mention the case where you find it fails

  • @piyushkumar2900
    @piyushkumar2900 6 месяцев назад +1

    NOT Recursive Soln,
    since data on nodes are >= 1 given int the test case, so when sum is 0 I did continue
    Just a simple level order traversal
    int isSumProperty(Node *root)
    {
    // Add your code here
    queue q;
    q.push(root);
    while(!q.empty()){
    int n = q.size();
    for(int i = 0;i < n;i++){
    int sum = 0;
    Node* node = q.front();
    q.pop();
    if(node->left){
    q.push(node->left);
    sum+=node->left->data;
    }
    if(node->right){
    q.push(node->right);
    sum+=node->right->data;
    }
    if(sum == 0) continue;
    if(node->data != sum) return false;
    }
    }
    return true;
    }

  • @nikhilprasad644
    @nikhilprasad644 3 года назад +13

    kindly make a video on this, where it is asked to find a binary tree as minimum as possible.
    I guess the interviewer might ask if we directly approach to O(n), then might change the qs to minimize the binary tree.
    thank you.

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

    can somebody post the question link

  • @RohitRaj-hl6ji
    @RohitRaj-hl6ji Год назад +2

    pretty hard for me not just this question but actually whole tree datastructure.

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

    such a easy to understand and easy to code solution and explanation for this question

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

    yes line 13 is not required on coming back from recursion we will handle that.

  • @suyashjaiswal4522
    @suyashjaiswal4522 2 года назад +5

    can we find the max value in a tree and then update the tree leaf nodes with this max value and while returning add the child nodes' values to the parent nodes 🤔🤔, the flaw I guess may be stack overflow but for smaller constraints, this soln can be used?

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

      There shouldn't be stack overflow since it's just a recursive DFS traversal, but it could probably lead to integer overflow.

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

      yeah u correct that works as well

  • @megaminds8903
    @megaminds8903 Месяц назад +1

    in which plateform we can solve this problem

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

    I got myself the answer in just 10 mins O(n) after solving 30+ tree qs :)

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

    **This is the basic approach which takes O(N) time complexity.**
    int solve(Node *root){
    if(!root) return 0;
    if(!root->left && !root->right) return root->data;
    int left = solve(root->left);
    int right = solve(root->right);
    if(left == -1 || right == -1) return -1;
    if(left + right != root->data) return -1;
    return root->data;

    }
    int isSumProperty(Node *root)
    {
    // Add your code here
    if(solve(root) == -1) return 0;
    return 1;
    }

  • @dr.owl_the_great
    @dr.owl_the_great 6 месяцев назад +1

    This problem is very vague , also without constraints this approach may exceed long long.

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

    What if all the values are negative. In that case the solution won’t work as adding two negative child number is decreasing the root value.?

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

    what if the maximum value in the BT is the maximum value accepted by C++? This will lead to overflow right? I think for loose constraints this will work.

  • @JalalMujawar
    @JalalMujawar 6 месяцев назад +2

    Got confused!!! I thought the video was for checking if the tree is having children sum property. Please change the title to "Convert binary tree to children sum tree", otherwise it's misleading.

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

    This question can be done like this ki take maximum of the tree and allow all the leaf nodes to be take the maximum value and then start updating the values from the leaf nodes.

  • @krishnamundada6034
    @krishnamundada6034 6 месяцев назад +1

    i am not getting to solve this question the link follows some other question

  • @argaming8596
    @argaming8596 9 месяцев назад +3

    where is the question link ???

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

    Really auesome

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

    if you provide the problem link it will be more helpful.. can you please ????

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

    ## Easy Approach
    1.queue ds taken to check every node
    2.check if leftdata and rightdata is there are not.
    3.if there --> addded
    else not equal to means return 0;
    4.to check every node add leftnode and right node
    ---------------just like level orderr-----------------------------------------
    public static int isSumProperty(Node root)
    {
    Queue q=new LinkedList();
    q.add(root);
    while(!q.isEmpty()){
    Node node=q.poll();
    int leftdata=(node.left!=null) ? node.left.data : 0;
    int rightdata=(node.right!=null) ? node.right.data : 0;
    if(node.left!=null || node.right!=null){
    if(node.data!=leftdata+rightdata) return 0;
    }
    if(node.left!=null) q.add(node.left);
    if(node.right!=null) q.add(node.right);
    }
    return 1;
    }

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

    5:55 - 6:30
    eDoC: 13:10

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

    Huge Respect Bhaiyya..❤👏

  • @pratik.784
    @pratik.784 Год назад +1

    what if it is minimum kind of question ?

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

    will it throw error when root node is INT_MAX?

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

    Self note:
    line no 13 redundant...since while coming back root will be assigned as sum of children

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

    Intuition(According to striver):
    As we go down we need to increase the node values ,so that whenever we recursively return back we will experience no shortage.
    public class Solution {
    public static int getAns(BinaryTreeNode root){
    if(root==null){
    return 0;
    }
    if(root.left ==null && root.right ==null){
    return root.data;
    }
    int left_val=root.left!=null?root.left.data:0;
    int righ_val=root.right!= null?root.right.data:0;
    if(left_val+righ_val root) {
    getAns(root);
    }
    }

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

    Another approach O(N):-
    void changeTree(Node*&root,int maxi){
    if(!root)return;
    if(!root->left&&!root->right){root->data=maxi;return;}
    helper(root->left,maxi);
    helper(root->right,maxi);
    int val=0;
    if(root->left)val+=root->left->data;
    if(root->right)val+=root->right->data;
    root->data=val;
    return;
    }
    void maxvalue(Node*root,int &maxi){
    if(!root)return;
    maxi=max(maxi,root->data);
    maxvalue(root->left,maxi);
    maxvalue(root->right,maxi);
    return;
    }

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

    Bro,remove else at line no 16,then correct result will be achieved

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

    can anyone share the link of gfg which has O(n^2) soution?

  • @abhinavsingh4221
    @abhinavsingh4221 2 года назад +6

    int postorder(Node* node, int parent) {
    if (!node) return 0;
    // if parent's value is greater than me then increase my value
    // because I can always increase parent's value but not decrease it
    node->val = max(node->val, parent);
    int left = postorder(node->left, node->val);
    int right = postorder(node->right, node->val);
    // if the sum of my child values is greater than me then increase my value to their sum
    if (node->val < left + right) {
    node->val = left + right;
    }
    // return my value to the parent so that parent can increase it's value if needed
    return node->val;
    }
    // caller method
    int main() {
    postorder(root, INT_MIN);
    }

  • @RamKumar-kz8gg
    @RamKumar-kz8gg 3 года назад +5

    there is no need of 13th line in cpp code

    • @takeUforward
      @takeUforward  3 года назад +1

      Yeah we can ignore that, realised later.

    • @RamKumar-kz8gg
      @RamKumar-kz8gg 3 года назад +1

      @@takeUforward thank you bhaiya for replying. actually maine isliye comment kiya ki agar kisi aur ko aisa doubt aaye to wo confirm ho jaaye ki wo shi hai.😄

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

    return (root->val == root->left->val + root->right->val);
    I solved it in a single line

  • @AkOp-bf9vm
    @AkOp-bf9vm 3 месяца назад

    what if we assign 0 to every node??

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

    Thank you for all your videos, awesome explanation

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

    in line 25, is this compulsory to write this condition for leaf node? or we can simply assign value tot into node, because for leaf node tot will automatically remains 0, so I does not matter

    • @anmolswarnkar7707
      @anmolswarnkar7707 3 года назад +3

      if we remove the if statement, the leaf nodes will become 0.

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

    what is that reorder at line no. 19 and 20 it should be changeTree na ?

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

    GOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOAT

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

    UNDERSTOOD;

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

    but still there will be out of bound case right.
    what if the root value is INT_MAX-1:
    and you assign same value to its children? while adding these can go out of bound right?
    please let me know if i am missing something?

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

    there are multiple syntax error in this code , it WILL NOT run on compiler

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

    Why all leaves of Binary Tree not holding same value for 1st test-case you took ?

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

    instead of just copying the root element to the child, can we take half of that and do the rest part same?
    will it work?

  • @rahatsshowcase8614
    @rahatsshowcase8614 3 года назад

    just a recursive post order traversal needed
    function Childrensum(root) {
    let validroot = isLeaf(root);
    if (validroot) return;
    Childrensum(root.left);
    Childrensum(root.right);
    let childrensum = 0;
    if (root.left) childrensum += root.left.data;
    if (root.right) childrensum += root.right.data;
    if (root.data > childrensum) root.left += root.data - childrensum;
    else if (root.data < childrensum) root.data = childrensum;
    return root;
    }

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

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

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

    What a nice solution sirji!!

  • @AB-tp9eg
    @AB-tp9eg 2 года назад

    I have one doubt, In an interview how to come up with a test case which is best for explanation, Because sometimes random test case cannot cover edge cases. Do we also need to mug up the test cases. Please reply.....

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

    Given N < 100, and if it is a skewed tree from leaf node it will calculate like 2*2*2*.... which will become very large, am i right or wrong?

  • @VIRAJBHOSLE
    @VIRAJBHOSLE 9 месяцев назад

    else if at line 16 is not required. only if suffice

  • @akulajyoshnavi
    @akulajyoshnavi 11 месяцев назад +1

    int ch(struct node * root,int m)
    {
    if(root==NULL)
    return 0;
    if(root->left==NULL&&root->right==NULL)
    {
    root->data=max(root->data,m);
    return root->data;
    }
    int l=ch(root->left,max(m,root->data));
    int r=ch(root->right,max(m,root->data));
    root->data=l+r;
    return root->data;
    }
    "We update each leaf node with the maximum value encountered along the root-to-leaf path to ensure that no node on this path holds a value lower than the maximum encountered so far. For, non-leaf we then compute the sum of their children's values and replace the parent's value with this sum."

  • @shivamsoni7754
    @shivamsoni7754 3 года назад +1

    Why we are changing the root Node, when Child node is greater than Parent Node. I think, This we can ignore. Because at the end , we are checking Root value..
    I think, this Part can be ignored
    if(child>=root->data? root->data=child).

  • @Yash-uk8ib
    @Yash-uk8ib 3 года назад +4

    line 16 is wrongly typed
    it should be "if" instead of "else if"

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

      NO!! It is correct because changing value of only one child make the sum of child nodes greater than parent node.

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

      @@ajiteshsaxena6015 But in the video itself we changed both the values of right and left

    • @Nikita-hv5jm
      @Nikita-hv5jm 2 года назад

      @@ajiteshsaxena6015 yaa u r right too but even if we do simply if for both...like change both left nd right then also the code will be correct , right ??

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

    Why does the code looks so easy after seeing but when i try by self i go blank😭😭😭

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

    can anyone explain why should we update parent sum with children's sum if parent sum is less than children sum before recursive call.

  • @Yash-uk8ib
    @Yash-uk8ib 3 года назад +1

    sir, when the sum of children > node, I think it is feasible to just assign nodes value to left and right and add them up while backtracking(same as what u did for sum of children < node). What i mean to say is just give the node's value to the children and add them up while backtracking. Is it correct??

    • @takeUforward
      @takeUforward  3 года назад

      Yess

    • @Yash-uk8ib
      @Yash-uk8ib 3 года назад

      @@takeUforward thanku sir

    • @saikrishnalanka133
      @saikrishnalanka133 3 года назад

      @@Yash-uk8ib i think approach stated by you fails when for example you have node value as 45 and its children values are say (50,30). in this case 50+30 > node . But we cannot just assign 45 to a child which is containing 30 as it cannot be decreased. Correct me if I understood this wrong.

    • @Yash-uk8ib
      @Yash-uk8ib 3 года назад

      @@saikrishnalanka133 u r correct, but I meant that just flood up every node with a greater value so while backtracking u just have to add them, no need to check greater or smaller

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

    why cant we make every node value 0 ??

    • @solarsystem9156
      @solarsystem9156 7 месяцев назад

      we can't decrease the node value. thats why

  • @charlesbabbage6786
    @charlesbabbage6786 9 месяцев назад

    Brilliant!

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

    Bhayya can't it be done without adding left and right if childsum> root to the root
    i.e if block Bcz i think it can work

  • @apmotivationakashparmar722
    @apmotivationakashparmar722 3 месяца назад

    Thank you so much !

  • @bhanureddy2087
    @bhanureddy2087 3 месяца назад

    this is wrong right? why is there an else if
    if (root->left) {
    root->left->val = root->val;
    } else if (root->right) {
    root->right->val = root->val;
    }
    it should be both if's only

  • @kartikaymahajan9591
    @kartikaymahajan9591 3 года назад +1

    line 16 i think instead of else if it should be only if

  • @abhishekkumar-fe8lw
    @abhishekkumar-fe8lw 10 месяцев назад

    where is the link for this question?

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

    won't it overflow when max element is big and number of nodes is upto 2e5?

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

      in this contion we have to increase always , but the constrain you are talking about, we can do this question with same approach without writing 13 line and above stuff , there never overflow will occur.

  • @srichandralolla7456
    @srichandralolla7456 3 месяца назад +1

    wow

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

    can any one explain how the space complexity is O(N)?? please...

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

    Yo yo yo Striver Bhaiya rocks

  • @amandeshpande8981
    @amandeshpande8981 3 года назад +1

    Self Explainatory CPP code:
    void reorder(BinaryTreeNode < int > * root){
    if(root==NULL){
    return;
    }

    int sumofChildren = 0;
    if(root->left){
    sumofChildren+=root->left->data;
    }
    if(root->right){
    sumofChildren+=root->right->data;
    }

    if(sumofChildrendata){
    if(root->left){
    root->left->data=root->data;
    }
    if(root->right){
    root->right->data=root->data;
    }
    }else{
    root->data=sumofChildren;
    }

    // go left then go right
    reorder(root->left);
    reorder(root->right);

    // while coming back
    int total = 0;
    if(root->left){
    total+=root->left->data;
    }
    if(root->right){
    total+=root->right->data;
    }
    // just check if any one of left or right exists
    if(root->left || root->right){
    root->data=total;
    }
    }

  • @VimanshMahajan
    @VimanshMahajan 7 месяцев назад

    Level Order Traversal can solve it as well and with much better intuition
    int isSumProperty(Node *root)
    {
    queue q;
    q.push(root);
    while(!q.empty()){
    Node* node = q.front();
    q.pop();
    int left = 0;
    int right = 0;
    if(node->left){
    left+=node->left->data;
    q.push(node->left);
    }
    if(node->right){
    right+=node->right->data;
    q.push(node->right);
    }
    if(left+right != 0 && left+right != node->data){
    return 0;
    }
    }
    return 1;
    }
    => we check left + right != 0 to consider that leaf nodes cannot have a child.

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

    In line 16 of C++ code, i think there should be an 'if' instead of 'else if'. Or am i missing something ?? Someone please clarify.

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

      I just checked, and the code works fine for both 'if' and 'else if'. How is this making sense ? Someone please explain 🙏🙏

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

      @@jatinchoubey6053 we reassign the values to left and right children because we want the sum to be greater than the root node. Hence, striver assigned both the children values to the root node only. We can also just assign any one of the children values to root value as the sum of this child's value and the other child's value (which is always positive) will anyways be greater than the root node

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

    Understood

  • @SachinSingh-oy6cq
    @SachinSingh-oy6cq 2 года назад

    Really helped a lot, thanks a lot

  • @vipuljain3643
    @vipuljain3643 3 года назад +1

    Bhaiya if root value is less than sum of children then we don't need to change the value of node(line 13). I am right Or not??

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

    line 13 is not required

  • @assymptote6787
    @assymptote6787 3 года назад +3

    line no.- 16 it will be if and not else if i guess🙄🙄