I'm currently working on LeetCode problem 814, "Binary Tree Pruning," and I've encountered some difficulties with my implementation. The problem requires returning a modified binary tree where every subtree not containing a value of 1 has been removed.
Here's my initial code:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root is None:
return None
self.pruneTree(root.left)
self.pruneTree(root.right)
if root.val == 0 and root.left is None and root.right is None:
root = None
return
return root
Unfortunately, my implementation did not produce the expected results and caused errors. However, when I consulted with others, they suggested the following code, which works correctly:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root is None:
return None
root.left = self.pruneTree(root.left)
root.right = self.pruneTree(root.right)
if root.val == 0 and root.left is None and root.right is None:
root = None
return
return root
I'm having trouble understanding why my initial solution, which doesn't utilize the root.left
and root.right
variables, didn't work as expected, while the modified solution provided by others does. I would appreciate it if someone could shed some light on this and help me understand the underlying issue.
Thank you in advance for your assistance!