Re: [闲聊] 每日leetcode

楼主: sustainer123 (caster)   2024-04-16 12:07:22
※ 引述《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
作者: digua (地瓜)   2024-04-16 12:10:00
大师
作者: SecondRun (雨夜琴声)   2024-04-16 12:13:00
大师
作者: JIWP (JIWP)   2024-04-16 12:21:00
别卷了
作者: DJYOSHITAKA (Evans)   2024-04-16 12:23:00
剩我写不了了

Links booklink

Contact Us: admin [ a t ] ucptt.com