Re: [闲聊] 每日LeetCode

楼主: pandix (面包屌)   2022-10-05 09:40:08
※ 引述《Rushia (みけねこ的鼻屎)》之铭言:
: 623. Add One Row to Tree
: 给予一个二元树,我们要在高度为depth的位置插入一行数值为val的节点。
: 若depth为1,因为没有存在深度为0的树所以令root为新的节点的左树。
: Example 1:
: https://assets.leetcode.com/uploads/2021/03/15/addrow-tree.jpg
: Input: root = [4,2,6,3,1,5], val = 1, depth = 2
: Output: [4,1,1,2,null,null,6,3,1,5]
又是以前写过的题目 重写一次方法也几乎一样 果然是我
depth 1 的时候建一个新的 root
depth 2 的时候在左右插新的 node
depth > 2 的时候 recursive 向下
class Solution:
def addOneRow(self, root: Optional[TreeNode], val: int, depth: int) ->
Optional[TreeNode]:
if depth == 1:
root = TreeNode(val, root, None)
elif depth == 2:
root.left = TreeNode(val, root.left, None)
root.right = TreeNode(val, None, root.right)
else:
if root.left:
self.addOneRow(root.left, val, depth-1)
if root.right:
self.addOneRow(root.right, val, depth-1)
return root
作者: Jaka (Jaka)   2021-10-05 09:40:00
大师
作者: Ericz7000 (Ericz7000nolan)   2022-10-05 09:43:00
大师
作者: Rushia (みけねこ的鼻屎)   2022-10-05 09:44:00
大师
作者: sustainer123 (caster)   2022-10-05 09:47:00
大师
作者: JerryChungYC (JerryChung)   2022-10-05 10:23:00
大师

Links booklink

Contact Us: admin [ a t ] ucptt.com