623. Add One Row to Tree
Medium
Input: root = [4,2,6,3,1,5], val = 1, depth = 2
Output:
[4,1,1,2,null,null,6,3,1,5]Input: root = [4,2,null,3,1], val = 1, depth = 3
Output:
[4,2,null,1,1,3,null,null,1]Last updated
Input: root = [4,2,6,3,1,5], val = 1, depth = 2
Output:
[4,1,1,2,null,null,6,3,1,5]Input: root = [4,2,null,3,1], val = 1, depth = 3
Output:
[4,2,null,1,1,3,null,null,1]Last updated
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