15% off all plans & roadmaps Use code
See plansProblem editorial
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.
Delete Leaves With a Given Value is a Tree Traversal Patterns (DFS & BFS) problem, in the Recursive Postorder Traversal subpattern. The pattern covers preorder, inorder, level order traversal, LCA, and serialization
The reference solution runs in O(n), where n is the number of nodes in the tree. time and O(h) auxiliary space for recursion, where h is the tree height. space.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Delete Leaves With a Given Value is a Tree Traversal Patterns (DFS & BFS) problem, in the Recursive Postorder Traversal subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.