Re: [閒聊] 每日leetcode已回收

看板Marginalman作者 (caster )時間1年前 (2024/05/17 14:14), 編輯推噓5(506)
留言11則, 9人參與, 1年前最新討論串234/1554 (看更多)
※ 引述《Rushia (早瀬ユウカの体操服 )》之銘言: : 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 : --------------------------------------------- 思路: 差不多 其實就DFS然後找到葉節點且符合目標值就刪除 Python Code: # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]: def dfs(node): if not node : return None node.right = dfs(node.right) node.left = dfs(node.left) if not node.left and not node.right and node.val == target: return None return node return dfs(root) -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.43.131.26 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1715926470.A.F98.html

05/17 14:15, 1年前 , 1F
別卷了
05/17 14:15, 1F

05/17 14:15, 1年前 , 2F
大師
05/17 14:15, 2F

05/17 14:15, 1年前 , 3F
我要被你卷死了
05/17 14:15, 3F

05/17 14:15, 1年前 , 4F
你都上岸了 對啊
05/17 14:15, 4F

05/17 14:18, 1年前 , 5F
泥板剩我DFS還要翻課本抄了
05/17 14:18, 5F

05/17 14:20, 1年前 , 6F
別卷了
05/17 14:20, 6F

05/17 14:21, 1年前 , 7F
大師 救我
05/17 14:21, 7F

05/17 14:21, 1年前 , 8F
佬 教
05/17 14:21, 8F

05/17 14:24, 1年前 , 9F
我文組廢物
05/17 14:24, 9F

05/17 14:26, 1年前 , 10F
你是下一個姑姑魯
05/17 14:26, 10F

05/17 14:39, 1年前 , 11F
別卷了
05/17 14:39, 11F
文章代碼(AID): #1cHlN6-O (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1cHlN6-O (Marginalman)