Delete Leaves With a Given Value LeetCode solution in C++

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),
10
* right(right) {}
11
* };
12
*/
13
class Solution {
14
public:
15
TreeNode *removeLeafNodes(TreeNode *root, int target) {
16
if (root == NULL || root->left == NULL && root->right == NULL && root->val == target)
17
return NULL;
18

19
root->left = removeLeafNodes(root->left, target);
20
root->right = removeLeafNodes(root->right, target);
21

22
if (root->left == NULL && root->right == NULL && root->val == target) {
23
return NULL;
24
}
25

26
return root;
27
}
28
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0