d
and the integer value v
for the nodes to be added?d
is 1?Here’s a Python solution for the problem:
# 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
def addOneRow(root: TreeNode, v: int, d: int) -> TreeNode:
if d == 1:
new_root = TreeNode(v)
new_root.left = root
return new_root
def dfs(node, depth):
if not node:
return
if depth == d - 1:
old_left = node.left
old_right = node.right
node.left = TreeNode(v)
node.right = TreeNode(v)
node.left.left = old_left
node.right.right = old_right
else:
dfs(node.left, depth + 1)
dfs(node.right, depth + 1)
dfs(root, 1)
return root
d
is 1, we create a new root node with value v
, and the old tree becomes the left subtree of this new node.d
.d-1
, add new nodes with value v
as the left and right children.n
is the number of nodes in the tree. Each node is visited once.h
is the height of the tree, corresponding to the recursive call stack.If you have any questions or need further clarifications or modifications in the code, please let me know!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?