Problem
We are given the head node root
of a binary tree, where additionally every node’s value is either a 0 or a 1.
Return the same tree where every subtree (of the given tree) not containing a 1 has been removed.
(Recall that the subtree of a node X is X, plus every node that is a descendant of X.)
Examples
1 | Input: [1,null,0,0,1] |
1 | Input: [1,0,1,0,0,0,1] |
1 | Input: [1,1,0,1,1,0,1,0] |
Solution
Method: Depth-first Search
Time Complexity: O(n)
Space Complexity:
1 | class Solution: |