作者:
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