美文网首页
814. Binary Tree Pruning

814. Binary Tree Pruning

作者: GoDeep | 来源:发表于2018-05-05 16:01 被阅读0次

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
            
        

相关文章

网友评论

      本文标题:814. Binary Tree Pruning

      本文链接:https://www.haomeiwen.com/subject/gfcerftx.html