Binary Tree Pruning

MediumTreesdfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given the root of a binary tree in which every node's value is 0 or 1. Remove every subtree that does not contain at least one 1. Return the root of the pruned tree. If the whole tree is removed, return an empty tree (null, serialized as []).

Examples

Input: root = [1,null,0,0,1]
Output: [1,null,0,null,1]
The left child of the 0 node holds only a 0, so it is removed. The 0 node itself stays because its right subtree has a 1.
Input: root = [1,0,1,0,0,0,1]
Output: [1,null,1,null,1]
The root's entire left subtree is zeros.
Input: root = [0,0,0]
Output: []
No node is 1, so everything is removed.

Constraints

  • 1 <= number of nodes <= 200
  • `Node.val` is `0` or `1`

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More dfs problems