Binary Tree Pruning — LeetCode 814 Python Solution

MediumTreeDepth-First SearchBinary Tree
Problem
#814
Reading time
3 min

The problem

Given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed. A subtree of a node node is node plus every node that is a descendant of node.

Example

Input
root = [1,null,0,0,1]
Output
[1,null,0,null,1]
Explanation
Only the red nodes satisfy the property "every subtree not containing a 1".

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if root is None:
            return root
        root.left = self.pruneTree(root.left)
        root.right = self.pruneTree(root.right)
        if root.val == 0 and root.left == root.right:
            return None
        return root

Complexity

MeasureComplexity
TimeO(V+E)
SpaceO(V) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 814. Binary Tree Pruning is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 814. Binary Tree Pruning?
LeetCode 814. Binary Tree Pruning is rated Medium on LeetCode.
What is the time complexity of LeetCode 814. Binary Tree Pruning?
The Python solution on this page runs in O(V+E).
What is the space complexity of LeetCode 814. Binary Tree Pruning?
The Python solution on this page uses O(V) auxiliary space.
What topics does LeetCode 814. Binary Tree Pruning cover?
LeetCode 814. Binary Tree Pruning is tagged Tree, Depth-First Search and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview