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
. For example:
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 either 0 or 1.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def pruneTree(root: TreeNode) -> TreeNode:
def contains_one(node: TreeNode) -> bool:
if not node:
return False
left_contains_one = contains_one(node.left)
right_contains_one = contains_one(node.right)
if not left_contains_one:
node.left = None
if not right_contains_one:
node.right = None
return node.val == 1 or left_contains_one or right_contains_one
if not contains_one(root):
return None
return root
pruneTree(root: TreeNode) -> TreeNode
: Main function to prune the tree.
contains_one(node: TreeNode) -> bool
to recursively check if a subtree contains at least one node with value 1.None
.contains_one(node: TreeNode) -> bool
: Recursive helper function.
None
, return False
.node.left = None
.node.right = None
.True
if the current node's value is 1 or if either the left or right subtrees contain 1, otherwise returns False
.Consider the input root = [1,null,0,0,1]
pruneTree
function is called with the root node (value 1).contains_one
function is called on the root:
contains_one
on the left child (None), which returns False
.contains_one
on the right child (value 0).
contains_one
calls contains_one
on its left child (value 0) which returns False
and sets node.left = Nonecontains_one
calls contains_one
on its right child (value 1) which returns True
True
.True
because its own value is 1.pruneTree
function returns the modified root.contains_one
function visits each node once.root
is None
, the function should return None
.None
.None
if its value is 0.