Skip to content

1325. Delete Leaves With a Given Value 👍

  • Time: $O(n)$
  • Space: $O(h)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  TreeNode* removeLeafNodes(TreeNode* root, int target) {
    if (root == nullptr)
      return nullptr;
    root->left = removeLeafNodes(root->left, target);
    root->right = removeLeafNodes(root->right, target);
    return isLeaf(root) && root->val == target ? nullptr : root;
  }

 private:
  bool isLeaf(TreeNode* root) {
    return root->left == nullptr && root->right == nullptr;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public TreeNode removeLeafNodes(TreeNode root, int target) {
    if (root == null)
      return null;
    root.left = removeLeafNodes(root.left, target);
    root.right = removeLeafNodes(root.right, target);
    return isLeaf(root) && root.val == target ? null : root;
  }

  private boolean isLeaf(TreeNode root) {
    return root.left == null && root.right == null;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def removeLeafNodes(
      self,
      root: TreeNode | None,
      target: int,
  ) -> TreeNode | None:
    if not root:
      return None
    root.left = self.removeLeafNodes(root.left, target)
    root.right = self.removeLeafNodes(root.right, target)
    return None if self._isLeaf(root) and root.val == target else root

  def _isLeaf(self, root: TreeNode | None) -> bool:
    return not root.left and not root.right