Skip to content

Commit

Permalink
Time: 42 ms (83.50%), Space: 17.7 MB (73.75%) - LeetHub
Browse files Browse the repository at this point in the history
  • Loading branch information
ChiragKr04 committed Apr 16, 2024
1 parent c024403 commit e1d403c
Showing 1 changed file with 23 additions and 9 deletions.
32 changes: 23 additions & 9 deletions 0623-add-one-row-to-tree/0623-add-one-row-to-tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,30 @@ def addOneRow(self, root: Optional[TreeNode], val: int, depth: int) -> Optional[
if depth == 1:
return 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)
queue = [root]

while 0 < len(queue):

depth -= 1

count = len(queue)

for _ in range(count):
node = queue.pop(0)

if node.left is not None:
queue.append(node.left)

if node.right is not None:
queue.append(node.right)

if depth == 1:
node.left = TreeNode(val, node.left, None)
node.right = TreeNode(val, None, node.right)

if depth == 1:
break

return root


Expand Down

0 comments on commit e1d403c

Please sign in to comment.