Untitled
unknown
plain_text
10 months ago
820 B
3
Indexable
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public class Solution {
public TreeNode removeLeafNodes(TreeNode root, int target) {
if (root == null) return null;
// Recursively process the left and right subtrees
root.left = removeLeafNodes(root.left, target);
root.right = removeLeafNodes(root.right, target);
// If the current node is a leaf and matches the target, delete it
if (root.left == null && root.right == null && root.val == target) {
return null;
}
return root;
}
}
Editor is loading...
Leave a Comment