码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode814 Binary Tree Pruning

时间:2020-02-13 22:59:44      阅读:82      评论:0      收藏:0      [点我收藏+]

标签:tis   def   class   red   pre   same tree   bsp   HERE   tput   

 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

 

leetcode814 Binary Tree Pruning

标签:tis   def   class   red   pre   same tree   bsp   HERE   tput   

原文地址:https://www.cnblogs.com/yawenw/p/12305571.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!