Loading...
You are given a binary tree root where every node's value is 0 or 1.
Remove every subtree whose nodes are all 0. A subtree is a node together with all of its descendants.
Return the root of the pruned tree. If every node is removed, return an empty tree.
Your function receives root as a TreeNode and returns the root of the pruned tree, or the empty tree (as null) if nothing survives. The node type is provided for you, with val, left, and right fields.
The examples below write trees as their level-order traversal, where null marks a missing child of a listed node and trailing nulls are omitted. That is only how trees are displayed; the encoding and decoding are done for you.
root is in the range [1,104].Node.val is either 0 or 1.The right child's own right child (value `1`) survives, so the right child (value `0`) is kept only as a connector; its left child (value `0`, a leaf) is pruned since there is no `1` anywhere in it.
The whole left subtree of the root (rooted at the left `0`) contains no `1`, so it is pruned entirely. In the right subtree, only the path down to the surviving `1` leaf remains.
The single node is `0` with no children, so the whole tree is pruned and the result is empty.
Click "Run" to test with sample cases or "Submit" to run all tests.