stillnotred

Untitled

Mar 20th, 2025
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8.  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9.  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10.  * };
  11.  */
  12.  
  13. class Solution {
  14. public:
  15.     TreeNode* sufficientSubset(TreeNode* root, int limit, int sum = 0) {
  16.         if(root == nullptr){
  17.             return nullptr;
  18.         }
  19.  
  20.  
  21.         // nsum = 5 + 4
  22.         int nsum = sum + root->val;
  23.  
  24.         if(root->left == nullptr && root->right == nullptr){
  25.             // leaf node hai ki nahi
  26.  
  27.             if(nsum < limit){
  28.                 return nullptr;
  29.             }
  30.             else{
  31.                 return root;
  32.             }
  33.         }
  34.         else{
  35.            
  36.             root->left = sufficientSubset(root->left,limit,nsum);
  37.             root->right = sufficientSubset(root->right,limit,nsum);
  38.  
  39.             if(root->left == nullptr && root->right == nullptr){
  40.                 return nullptr;
  41.             }
  42.             else{
  43.                 return root;
  44.             }
  45.         }
  46.     }
  47. };
Advertisement
Add Comment
Please, Sign In to add comment