[LeetCode] Delete Leaves With a Given Value

1325. Delete Leaves With a Given Value

Given a binary tree root and an integer target, delete all the leaf nodes with value target.

Note that once you delete a leaf node with value target, if its parent node becomes a leaf node and has the value target, it should also be deleted (you need to continue doing that until you cannot).

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
/**
* 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 {
bool isLeafTarget(TreeNode* node, int& target) {
return node->val == target and node->left == nullptr and node->right == nullptr;
}
void travel(TreeNode* node, int& target) {
if(node->left) {
travel(node->left, target);
if(isLeafTarget(node->left, target)) {
node->left = nullptr;
}
}
if(node->right) {
travel(node->right, target);
if(isLeafTarget(node->right, target)) {
node->right = nullptr;
}
}
}
public:
TreeNode* removeLeafNodes(TreeNode* root, int target) {
TreeNode* dummy = new TreeNode(-1, root, nullptr);
travel(dummy, target);
return dummy->left;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/09/PS/LeetCode/delete-leaves-with-a-given-value/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.