首页 > 其他 > 详细

leetcode1325

时间:2020-01-19 21:26:27      阅读:94      评论:0      收藏:0      [点我收藏+]
 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。

leetcode1325

原文:https://www.cnblogs.com/asenyang/p/12215619.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!