We are given the head node root of a binary tree, where additionally every node's value is either a 0 or a 1.
Return the same tree where every subtree (of the given tree) not containing a 1 has been removed.
(Recall that the subtree of a node X is X, plus every node that is a descendant of X.)
image.png
image.png
递归递归递归
class Solution:
def pruneTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root: return root
root.left, root.right = self.pruneTree(root.left), self.pruneTree(root.right)
if not root.val and not root.left and not root.right:
return None
return root
网友评论