Re: [闲聊] 每日leetcode

楼主: argorok (s.green)   2024-04-16 09:58:32
: 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
作者: JIWP (JIWP)   2024-04-16 10:01:00
别卷了
作者: DJYOSHITAKA (Evans)   2024-04-16 10:08:00
别卷了

Links booklink

Contact Us: admin [ a t ] ucptt.com