Given the root of a binary tree and two integers val and depth, add a row of nodes with value val at the given depth depth.
Note that the root node is at depth 1.
The adding rule is:
For this problem, there are two cases to handle, when depth == 1 and otherwise.
When depth == 1, as the problems states, we create a new node with val, and set its left subtree to the tree.
def addOneRow(root: Optional[TreeNode], val: int, depth: int) -> Optional[TreeNode]:
if depth == 1:
= TreeNode(val, root, None)
new_node return new_node
For all other cases, we want to keep track of the depth and when we hit depth - 1, we want to implement the logic of the problem:
Finally, we can return here because we don’t need to process the rest of the tree.
def traverse(node, curr_depth, parent):
if not node:
return
if curr_depth == depth - 1:
= TreeNode(val, node.left, None)
new_left = TreeNode(val, None, node.right)
new_right = new_left
node.left = new_right
node.right return
+ 1, node)
traverse(node.left, curr_depth + 1, node) traverse(node.right, curr_depth