Binary Tree Pruning

medium trees dfs recursion

Problem

Given the root of a binary tree containing 0s and 1s, return the same tree with every subtree not containing any 1 removed.

Inputroot = [1,null,0,0,1]
Output[1,null,0,null,1]
The 0-only left subtree of the right child is pruned.

def pruneTree(root):
    if root is None:
        return None
    root.left = pruneTree(root.left)
    root.right = pruneTree(root.right)
    if root.val == 0 and root.left is None and root.right is None:
        return None
    return root
var pruneTree = function(root) {
    if (!root) return null;
    root.left = pruneTree(root.left);
    root.right = pruneTree(root.right);
    if (root.val === 0 && !root.left && !root.right) return null;
    return root;
};
class Solution {
    public TreeNode pruneTree(TreeNode root) {
        if (root == null) return null;
        root.left = pruneTree(root.left);
        root.right = pruneTree(root.right);
        if (root.val == 0 && root.left == null && root.right == null) return null;
        return root;
    }
}
class Solution {
public:
    TreeNode* pruneTree(TreeNode* root) {
        if (!root) return nullptr;
        root->left = pruneTree(root->left);
        root->right = pruneTree(root->right);
        if (root->val == 0 && !root->left && !root->right) return nullptr;
        return root;
    }
};
Time: O(n) Space: O(h)