Re: [閒聊] 每日leetcode已回收
https://leetcode.com/problems/delete-leaves-with-a-given-value/description/
1325. Delete Leaves With a Given Value
給你一個二元樹和一個數字 target,刪除所有葉子節點是 target 的節點,如果刪除後
新的葉子節點也是 target 也要刪除。
思路:
1.如果遇到葉子節點且是target就刪除他並返回null,每次檢查之間要先dfs,如果dfs
返回null就刪除子節點。
py code:
---------------------------------------------
class Solution:
def removeLeafNodes(self, root: Optional[TreeNode], target: int) ->
Optional[TreeNode]:
if not root:
return None
root.left = self.removeLeafNodes(root.left, target)
root.right = self.removeLeafNodes(root.right, target)
if not root.left and not root.right and root.val == target:
return None
return root
---------------------------------------------
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 101.138.217.141 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1715909221.A.67F.html
推
05/17 09:27,
1年前
, 1F
05/17 09:27, 1F
推
05/17 09:34,
1年前
, 2F
05/17 09:34, 2F
→
05/17 10:16,
1年前
, 3F
05/17 10:16, 3F
討論串 (同標題文章)
以下文章回應了本文 (最舊先):
完整討論串 (本文為第 233 之 1554 篇):