nikunjsoni

814

Jul 23rd, 2021
97
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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. class Solution {
  13. public:
  14.     TreeNode* pruneTree(TreeNode* root) {
  15.         return dfs(root) ? root : NULL;
  16.     }
  17.    
  18.     bool dfs(TreeNode* root){
  19.         if(!root) return false;
  20.        
  21.         bool left = dfs(root->left);
  22.         bool right = dfs(root->right);
  23.        
  24.         if(!left) root->left = NULL;
  25.         if(!right) root->right = NULL;
  26.        
  27.         return (root->val == 1 || left || right);
  28.     }
  29. };
RAW Paste Data