zoukankan      html  css  js  c++  java
  • leetcode1325

     1 class Solution:
     2     def __init__(self):
     3         self.tag = True
     4     
     5     def preOrder(self,root,target):
     6         if root != None:
     7             if root.left != None:
     8                 if root.left.left == None and root.left.right == None and root.left.val == target:
     9                     root.left = None
    10                     self.tag = True
    11                 else:
    12                     self.preOrder(root.left,target)
    13             if root.right != None:
    14                 if root.right.left == None and root.right.right == None and root.right.val == target:
    15                     root.right = None
    16                     self.tag = True
    17                 else:
    18                     self.preOrder(root.right,target)
    19             
    20         
    21     def removeLeafNodes(self, root: TreeNode, target: int) -> TreeNode:
    22         while root != None and self.tag:
    23             self.tag = False
    24             self.preOrder(root,target)
    25             if root.left == None and root.right == None and root.val == target:
    26                 return None
    27         return root

    多次从跟节点遍历树,判断是否有叶子节点的值等于target,如果有这样的叶子节点就将其删除。

    使用一个bool值记录本轮是否删除过叶子节点,如果本轮删除过,则再重新从根节点进行一次检查。

    一直到当前轮没有删除过叶子节点,则返回树。

    如果已经把树删成了空树,则返回None。

  • 相关阅读:
    Travis 编译使用 JDK 的版本
    《程序员的职业素养》读书笔记
    先做人,在做事
    CAP理论
    ZGC实践
    虚拟化技术的分类及介绍
    C# AD域验证登录
    dotnet core 3.1 站点发布成windows服务
    windows 服务无法调用office word COM接口
    Ext 动态加载js文件
  • 原文地址:https://www.cnblogs.com/asenyang/p/12215619.html
Copyright © 2011-2022 走看看