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

看板Marginalman作者 (早瀬ユウカの体操服 )時間1年前 (2024/04/16 09:16), 編輯推噓1(100)
留言1則, 1人參與, 1年前最新討論串122/1548 (看更多)
https://leetcode.com/problems/add-one-row-to-tree 623. Add One Row to Tree 給你一個二元樹,請在深度為depth的位置插入一列值為val的節點。 思路: 1.用 bfs 算深度找到 depth - 1 的位置,直接插入。 2.depth == 1 是 corner case 要額外處理。 py code: --------------------------------------------------------- class Solution: def addOneRow(self, root: Optional[TreeNode], val: int, depth: int) -> Optional[TreeNode]: if depth == 1: return TreeNode(val, root, None) q = deque() q.append(root) h = 1 while q: size = len(q) for i in range(size): x = q.popleft() if h == depth - 1: x.left = TreeNode(val, x.left, None) x.right = TreeNode(val, None, x.right) continue if x.left: q.append(x.left) if x.right: q.append(x.right) h += 1 return root --------------------------------------------------------- -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 101.139.50.149 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1713230197.A.D65.html

04/16 09:19, 1年前 , 1F
大師
04/16 09:19, 1F
文章代碼(AID): #1c7T5rrb (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1c7T5rrb (Marginalman)