Delete Leaves With a Given Value

MediumTreeDepth-First SearchBinary Tree

Solution

import { TreeNode } from '@algorithm/lib';
 
export function removeLeafNodes(root: TreeNode | null, target: number): TreeNode | null {
  if (root === null) {
    return null;
  }
  root.left = removeLeafNodes(root.left, target);
  root.right = removeLeafNodes(root.right, target);
  if (root.left === null && root.right === null && root.val === target) {
    return null;
  }
  return root;
}