Leetcode 814: Binary Tree Pruning

grid47
grid47
Exploring patterns and algorithms
Aug 17, 2024 5 min read

A binary tree where branches are pruned, with the pruned branches glowing softly as they are removed.
Solution to LeetCode 814: Binary Tree Pruning Problem

You are given the root of a binary tree. Your task is to remove all subtrees in the tree that do not contain at least one node with the value 1. A subtree is defined as the node and all its descendants. Return the modified tree.
Problem
Approach
Steps
Complexity
Input: You are given the root of a binary tree. The tree is represented as a series of node values in a binary tree structure.
Example: Input: root = [1,null,0,0,1]
Constraints:
• The number of nodes in the tree is between 1 and 200.
• Node values are either 0 or 1.
Output: Return the same binary tree where every subtree not containing a 1 has been removed. The returned tree should be in the same binary tree structure.
Example: Output: [1,null,0,null,1]
Constraints:
• The tree should be returned as a binary tree structure.
Goal: The goal is to prune the binary tree such that every subtree that does not contain a 1 is removed.
Steps:
• Traverse the tree in a post-order manner (visit left, right, then root).
• If a node's left and right subtrees do not contain any 1s, remove those subtrees.
• If the current node itself has a value of 0 and both subtrees are removed, prune the current node as well.
Goal: Ensure that the solution works for small trees with one node as well as for larger trees up to 200 nodes.
Steps:
• The binary tree has at least one node.
• The tree will not contain values other than 0 or 1.
Assumptions:
• The tree is valid and consists of integers either 0 or 1.
• Each node has at most two children.
Input: Input: root = [1,null,0,0,1]
Explanation: After pruning, the tree retains the root node with value 1, and only the right child containing a 1 remains. The left child is pruned because it does not contain any 1s.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus