Skip to content

Commit 5a7df90

Browse files
authored
Create delete-leaves-with-a-given-value.cpp
1 parent cd3fc67 commit 5a7df90

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// Time: O(n)
2+
// Space: O(h)
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* struct TreeNode {
7+
* int val;
8+
* TreeNode *left;
9+
* TreeNode *right;
10+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11+
* };
12+
*/
13+
14+
class Solution {
15+
public:
16+
TreeNode* removeLeafNodes(TreeNode* root, int target) {
17+
if (!root) {
18+
return nullptr;
19+
}
20+
root->left = removeLeafNodes(root->left, target);
21+
root->right = removeLeafNodes(root->right, target);
22+
return (root->left == root->right && root->val == target) ? nullptr : root;
23+
}
24+
};

0 commit comments

Comments
 (0)