forked from shruti170901/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBinary Tree Pruning.cpp
More file actions
29 lines (28 loc) · 888 Bytes
/
Binary Tree Pruning.cpp
File metadata and controls
29 lines (28 loc) · 888 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// https://leetcode.com/problems/binary-tree-pruning/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool elim(TreeNode* root){
if(root==NULL) return true;
if(root->val==1) return false;
return elim(root->left)&&elim(root->right);
}
TreeNode* pruneTree(TreeNode* root) {
if(root==NULL) return NULL;
if(elim(root->left)) root->left=NULL;
if(elim(root->right)) root->right=NULL;
root->left=pruneTree(root->left);
root->right=pruneTree(root->right);
return root;
}
};