Algorithm
Problem Name: 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
.
Example 1:
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". The diagram on the right represents the answer.
Example 2:
Input: root = [1,0,1,0,0,0,1] Output: [1,null,1,null,1]
Example 3:
Input: root = [1,1,0,1,1,0,1,0] Output: [1,1,0,1,1,null,1]
Constraints:
- The number of nodes in the tree is in the range
[1, 200]
. Node.val
is either0
or1
.
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
class Solution {
public:
TreeNode* pruneTree(TreeNode* root) {
if(!root) return NULL;
root->left = pruneTree(root->left);
root->right = pruneTree(root->right);
return (!root->val && !root->left && !root->right) ? NULL : root;
}
};
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Java Programming
Code -
Java Programming
class Solution {
public TreeNode pruneTree(TreeNode root) {
return subtreeContainsOne(root) ? root : null;
}
private boolean subtreeContainsOne(TreeNode root) {
if (root == null) {
return false;
}
boolean leftContains = subtreeContainsOne(root.left);
boolean rightContains = subtreeContainsOne(root.right);
if (!leftContains) {
root.left = null;
}
if (!rightContains) {
root.right = null;
}
return leftContains || rightContains || root.val == 1;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Python Programming
Code -
Python Programming
class Solution:
def pruneTree(self, root, parent = None):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root: return
left = self.pruneTree(root.left, root)
right = self.pruneTree(root.right, root)
if not left and not right and root.val == 0:
if parent and parent.left == root: parent.left = None
elif parent and parent.right == root: parent.right = None
return
else: return root
Copy The Code &
Try With Live Editor
Input
#4 Code Example with C# Programming
Code -
C# Programming
namespace LeetCode
{
public class _0814_BinaryTreePruning
{
public TreeNode PruneTree(TreeNode root)
{
if (root == null) return null;
if (root.left == null && root.right == null && root.val == 0) return null;
root.left = PruneTree(root.left);
root.right = PruneTree(root.right);
if (root.left == null && root.right == null && root.val == 0) return null;
return root;
}
}
}
Copy The Code &
Try With Live Editor
Input
Output