Skip to main content

623 - Add One Row to Tree

Details

KeyValue
Linkhttps://leetcode.com/problems/add-one-row-to-tree/
LanguagePython 3
Runtime85 ms, faster than 60.61% of Python3 online submissions for Add One Row to Tree
Memory Usage17.5 MB, less than 37.27% of Python3 online submissions for Add One Row to Tree
DatastructuresTreeNode
AlgorithmsDFS
ComplexityTime: O(N) Memory: O(N)

Procedure

  1. ...

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 not root or depth <= 0: return None

if depth == 1: return TreeNode(val, root, None)
if depth == 2:
root.left = TreeNode(val, root.left, None)
root.right = TreeNode(val, None, root.right)
else:
root.left == self.addOneRow(root.left, val, depth - 1)
root.right == self.addOneRow(root.right, val, depth - 1)

return root