Leetcode 814. Binary Tree Pruning
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
.
root
is null
)?
null
.null
.To solve this problem, we can utilize a recursive approach to traverse the tree in a post-order manner (left-right-root). At each node, we will:
null
.This ensures that subtrees that do not contain a 1
are removed from the tree.
/**
* 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: if root is null, return null
if (root == null) {
return null;
}
// Recursively prune the left and right subtrees
root.left = pruneTree(root.left);
root.right = pruneTree(root.right);
// If both left and right are null, and the current node value is 0, prune it (return null)
if (root.left == null && root.right == null && root.val == 0) {
return null;
}
// Otherwise, return the current node
return root;
}
}
This approach ensures that we traverse and modify the tree efficiently, removing subtrees that do not contain a 1
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?