1 """ 2 We are given the head node root of a binary tree, where additionally every node's value is either a 0 or a 1. 3 Return the same tree where every subtree (of the given tree) not containing a 1 has been removed. 4 (Recall that the subtree of a node X is X, plus every node that is a descendant of X.) 5 Example 1: 6 Input: [1,null,0,0,1] 7 Output: [1,null,0,null,1] 8 Explanation: 9 Only the red nodes satisfy the property "every subtree not containing a 1". 10 The diagram on the right represents the answer. 11 Example 2: 12 Input: [1,0,1,0,0,0,1] 13 Output: [1,null,1,null,1] 14 Example 3: 15 Input: [1,1,0,1,1,0,1,0] 16 Output: [1,1,0,1,1,null,1] 17 """ 18 """ 19 剪枝问题: 20 递归遍历,不用考虑递归左右顺序 21 如果结点值为0且,左右孩子为None 22 将该结点置为None 23 """ 24 class TreeNode: 25 def __init__(self, x): 26 self.val = x 27 self.left = None 28 self.right = None 29 30 class Solution: 31 def pruneTree(self, root): 32 if root == None: 33 return None 34 root.left = self.pruneTree(root.left) 35 root.right = self.pruneTree(root.right) 36 if root.val == 0 and root.left == None and root.right == None: #!!!判别式 37 return None 38 return root