814. Binary Tree Pruning ¶ Time: $O(n)$ Space: $O(h)$ C++JavaPython 1 2 3 4 5 6 7 8 9 10 11 12class Solution { public: TreeNode* pruneTree(TreeNode* root) { if (root == nullptr) return nullptr; root->left = pruneTree(root->left); root->right = pruneTree(root->right); if (root->left == nullptr && root->right == nullptr && root->val == 0) return nullptr; return root; } }; 1 2 3 4 5 6 7 8 9 10 11class Solution { public TreeNode pruneTree(TreeNode root) { if (root == null) 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; } } 1 2 3 4 5 6 7 8 9class Solution: def pruneTree(self, root: TreeNode | None) -> TreeNode | None: if not root: return None root.left = self.pruneTree(root.left) root.right = self.pruneTree(root.right) if not root.left and not root.right and not root.val: return None return root