zoukankan      html  css  js  c++  java
  • leetcode814 Binary Tree Pruning

     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
  • 相关阅读:
    Hadoop2.x环境搭建
    HDFS序列化
    Hadoop2.x介绍
    eclipse(1)----ubuntu下的安装与配置
    hive与hbase
    mysql----启动报错
    序列化+protobuff+redis
    爬虫学习笔记(2)--创建scrapy项目&&css选择器
    日常随笔
    spark学习(2)--hadoop安装、配置
  • 原文地址:https://www.cnblogs.com/yawenw/p/12305571.html
Copyright © 2011-2022 走看看