832. Binary Tree Pruning
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to prune a binary tree such that any subtree that does not contain the value 1 is removed. A subtree at a node includes the node itself and all its descendants. This implies that if a node has a value of 1, it and its ancestors will be preserved. The decision to prune a node's subtree is dependent on whether a 1 exists in the node itself, its left subtree, or its right subtree. This dependency on child subtrees suggests a recursive, post-order traversal approach.
Solution
Binary Tree Pruning in 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]:
# Base case for the recursion.
if not root:
return None
# This is a post-order traversal. We first recurse on the children.
# The returned value is the root of the pruned subtree, which we assign back.
root.left = self.pruneTree(root.left)
root.right = self.pruneTree(root.right)
# After children's subtrees are pruned, we decide about the current node.
# If the current node is 0 and has no children (they were pruned or never existed),
# this node should be pruned as well.
if root.val == 0 and not root.left and not root.right:
# Returning None effectively removes this node from its parent.
return None
# If the node's subtree contains a 1 (either the node itself or one of its descendants),
# it should be kept.
return root
Binary Tree Pruning in Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode pruneTree(TreeNode root) {
// Base case for recursion: if node is null, return null.
if (root == null) {
return null;
}
// Recursively prune left and right subtrees (post-order traversal).
// The children are processed before the parent node.
root.left = pruneTree(root.left);
root.right = pruneTree(root.right);
// After children are pruned, check if the current node should also be pruned.
// A node becomes a candidate for pruning if it is a leaf and its value is 0.
// A subtree of all 0s will be recursively pruned from the leaves up,
// so checking for a leaf with value 0 is sufficient here.
if (root.val == 0 && root.left == null && root.right == null) {
// By returning null, we are removing this node from the tree.
return null;
}
// If the node should not be pruned, return it.
return root;
}
}
Binary Tree Pruning in C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* pruneTree(TreeNode* root) {
// Base case for recursion: if the node is null, return null.
if (!root) {
return nullptr;
}
// Recursively prune left and right subtrees. This is a post-order traversal.
// We process children before the parent.
root->left = pruneTree(root->left);
root->right = pruneTree(root->right);
// After pruning the subtrees, check if the current node should be pruned.
// A node should be pruned if it's a leaf node with value 0. This works because
// any subtree full of 0s would have its nodes pruned from the bottom up,
// leaving its root as a leaf node with value 0 after its children are removed.
if (root->val == 0 && !root->left && !root->right) {
// Returning nullptr effectively disconnects this node from its parent.
return nullptr;
}
// If the node is not pruned, return it.
return root;
}
};
Binary Tree Pruning in TypeScript
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function pruneTree(root: TreeNode | null): TreeNode | null {
// Base case for recursion: if the current node is null, there is nothing to do.
if (!root) {
return null;
}
// Recursively prune left and right subtrees using a post-order traversal approach.
// We handle the children before the parent.
root.left = pruneTree(root.left);
root.right = pruneTree(root.right);
// After attempting to prune children, check if the current node should be pruned.
// A node is pruned if it has a value of 0 and has no children (either originally
// or after its children's subtrees containing only 0s were pruned).
if (root.val === 0 && root.left === null && root.right === null) {
// Returning null signifies to the parent call that this node should be removed.
return null;
}
// If the node is not pruned, return the node itself.
return root;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.