Leetcode 623 Solution

This article provides solution to leetcode question 623 (add-one-row-to-tree)

https://leetcode.com/problems/add-one-row-to-tree

Solution

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def addOneRow(self, root: TreeNode, v: int, d: int) -> TreeNode:
        if d == 1:
            new_root = TreeNode(v)
            new_root.left = root
            return new_root

        q = [root]
        d -= 1
        while q:
            if d == 1:
                break

            s = len(q)
            for _ in range(s):
                node = q.pop(0)

                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)

            d -= 1

        for node in q:
            new_left = TreeNode(v)
            new_right = TreeNode(v)

            new_left.left = node.left
            new_right.right = node.right

            node.left = new_left
            node.right = new_right

        return root