You are given the root of a binary tree in root and an integer target. A binary tree consists of nodes, each with a value and up to two children; a missing child is represented by null in the level-order input. A leaf is a node that has neither a left child nor a right child.
Remove every leaf whose value equals target. Deletions are applied repeatedly: after deleting a leaf, its parent may become a leaf, and that parent must also be deleted if its value equals target. A leaf with any other value remains in the tree.
Return the root of the resulting tree. If the original tree is empty or the root is eventually deleted, return an empty tree, represented as []. The returned tree is serialized in level order using null for missing children.
Example 1:
Input: root = [5,3,8,3,4,null,3], target = 3
Output: [5,3,8,null,4]
Explanation: The leftmost 3 and the right child of 8 are target-valued leaves, so they are removed. The other 3 still has child 4 and therefore is not a leaf, so it remains.
Example 2:
Input: root = [7,2,9,null,5,9,1], target = 9
Output: [7,2,9,null,5,null,1]
Explanation: The 9 that is the left child of the right-side 9 is a leaf and is removed. The other 9 remains because it still has child 1.
Example 3:
Input: root = [], target = 6
Output: []
Explanation: The input tree is empty, so there are no leaves to remove.
Constraints:
0 <= number of nodes in root <= 30001 <= value of each node <= 10001 <= target <= 1000root describes a valid binary tree in level orderroot is [] when the tree is emptytarget is a JSON integerNeed help or want more practice?