DEV Community

Karleb
Karleb

Posted on

1325. Delete Leaves With a Given Value

https://leetcode.com/problems/delete-leaves-with-a-given-value/?envType=daily-question&envId=2024-05-17

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} target
 * @return {TreeNode}
 */
var removeLeafNodes = function (root, target) {

    if (!root) return null

    root.left = removeLeafNodes(root.left, target)
    root.right = removeLeafNodes(root.right, target)

    if (root.val === target && !root.left && !root.right) {
        return null;
    }

    return root
};

Enter fullscreen mode Exit fullscreen mode

traverse the left and right sub-tree, get to the last node, if it is the target, remove it by making it null, else do nothing. Perform this recursively.

Top comments (0)