Leetcode 814. Binary Tree Pruning
You are given the root
of a binary tree where each node has a value of 0
or 1
. Prune the tree so that subtrees containing all 0
s are removed. A subtree of a node node
is node
plus every node that is a descendant of node
.
Return the same tree where every subtree (of the given tree) not containing a 1
has been removed.
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) {}
};
Can the input tree be empty?
Yes, the input tree can be empty (root
could be nullptr
).
nullptr
.1
, set the respective child pointer to nullptr
.nullptr
.Here’s an implementation 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) {
if (!root) {
return nullptr;
}
// Recursively prune the left and right subtrees
root->left = pruneTree(root->left);
root->right = pruneTree(root->right);
// If the current node's value is 0 and both subtrees are nullptr, prune this node
if (root->val == 0 && !root->left && !root->right) {
return nullptr;
}
return root;
}
};
0
and if both its left and right children are nullptr
.This approach ensures that unnecessary nodes are removed efficiently while preserving nodes that have or are required by nodes with the value 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?