精華區beta Marginalman 關於我們 聯絡資訊
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
oinishere: 大師 04/16 09:19