# 623. Add One Row to Tree

• Time: $O(n)$
• Space: $O(n)$
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 class Solution { public: TreeNode* addOneRow(TreeNode* root, int v, int d) { if (d == 1) { TreeNode* newRoot = new TreeNode(v); newRoot->left = root; return newRoot; } int depth = 0; queue q{{root}}; while (!q.empty()) { ++depth; for (int sz = q.size(); sz > 0; --sz) { TreeNode* node = q.front(); q.pop(); if (node->left) q.push(node->left); if (node->right) q.push(node->right); if (depth == d - 1) { TreeNode* cachedLeft = node->left; TreeNode* cachedRight = node->right; node->left = new TreeNode(v); node->right = new TreeNode(v); node->left->left = cachedLeft; node->right->right = cachedRight; } } if (depth == d - 1) break; } return root; } }; 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 class Solution { public TreeNode addOneRow(TreeNode root, int v, int d) { if (d == 1) { TreeNode newRoot = new TreeNode(v); newRoot.left = root; return newRoot; } int depth = 0; Queue q = new ArrayDeque<>(Arrays.asList(root)); while (!q.isEmpty()) { ++depth; for (int sz = q.size(); sz > 0; --sz) { TreeNode node = q.poll(); if (node.left != null) q.offer(node.left); if (node.right != null) q.offer(node.right); if (depth == d - 1) { TreeNode cachedLeft = node.left; TreeNode cachedRight = node.right; node.left = new TreeNode(v); node.right = new TreeNode(v); node.left.left = cachedLeft; node.right.right = cachedRight; } } if (depth == d - 1) break; } return root; } }