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

看板Marginalman作者 (caster )時間1年前 (2024/04/16 12:07), 編輯推噓3(301)
留言4則, 4人參與, 1年前最新討論串124/1548 (看更多)
※ 引述《argorok (死肥肥社管)》之銘言: : : https://leetcode.com/problems/add-one-row-to-tree : : 623. Add One Row to Tree : : 給你一個二元樹,請在深度為depth的位置插入一列值為val的節點。 : 今天遞迴解起來還蠻順的 : 感覺有點手感了 : class Solution(object): : def addOneRow(self, root, val, depth): : """ : :type root: TreeNode : :type val: int : :type depth: int : :rtype: TreeNode : """ : if depth == 1: : return TreeNode(val, left=root) : if depth == 2: : if root: : tmpLeft = TreeNode(val, left=root.left) : tmpRight = TreeNode(val, right=root.right) : root.left = tmpLeft : root.right = tmpRight : elif depth > 2: : if root.left: : self.addOneRow(root.left, val, depth-1) : if root.right: : self.addOneRow(root.right, val, depth-1) : return root 思路: bfs找到指定層數 然後把東西放進去 假設指定層數為一 直接在root前面放東西就好 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 addOneRow(self, root: Optional[TreeNode], val: int, depth: int) -> Optional[TreeNode]: if depth == 1: root = TreeNode(val,root,None) return root q = deque() q.append(root) h = 1 while q: l = len(q) for i in range(l): node = q.popleft() if h == depth - 1: node.left = TreeNode(val,node.left,None) node.right = TreeNode(val,None,node.right) if node.left: q.append(node.left) if node.right: q.append(node.right) h += 1 return root -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.43.137.148 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1713240445.A.E64.html

04/16 12:10, 1年前 , 1F
大師
04/16 12:10, 1F

04/16 12:13, 1年前 , 2F
大師
04/16 12:13, 2F

04/16 12:21, 1年前 , 3F
別卷了
04/16 12:21, 3F

04/16 12:23, 1年前 , 4F
剩我寫不了了
04/16 12:23, 4F
文章代碼(AID): #1c7Vbzva (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1c7Vbzva (Marginalman)