-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdelete-leaves-with-a-given-value.cpp
44 lines (43 loc) · 1.08 KB
/
delete-leaves-with-a-given-value.cpp
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* removeLeafNodes(TreeNode* root, int target) {
if (root == NULL) {
return NULL;
}
helper(root, target);
if ((root->val == target) && (root->left == NULL) && (root->right == NULL)) {
return NULL;
}
return root;
}
bool helper(TreeNode* root, int target) {
bool flag = false;
if (root == NULL) {
return false;
}
if (root->left) {
if (helper(root->left, target)) {
root->left = NULL;
}
}
if (root->right) {
if (helper(root->right, target)) {
root->right = NULL;
}
}
if ((root->val == target) && (root->left == NULL) && (root->right == NULL)) {
root = NULL;
flag = true;
}
return flag;
}
};