---
# System prepended metadata

title: 623. Add One Row to Tree

---

# 623. Add One Row to Tree

## Description
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:

Given the integer depth, for each not null tree node cur at the depth depth - 1, create two tree nodes with value val as cur's left subtree root and right subtree root.
cur's original left subtree should be the left subtree of the new left subtree root.
cur's original right subtree should be the right subtree of the new right subtree root.
If depth == 1 that means there is no depth depth - 1 at all, then create a tree node with value val as the new root of the whole original tree, and the original tree is the new root's left subtree.

## Example 1
![image](https://hackmd.io/_uploads/HkrwzLjx0.png)


>Input: root = [4,2,6,3,1,5], val = 1, depth = 2
Output: [4,1,1,2,null,null,6,3,1,5]

## Example 2
![image](https://hackmd.io/_uploads/rk0OGUoeR.png)

>Input: root = [4,2,null,3,1], val = 1, depth = 3
Output: [4,2,null,1,1,3,null,null,1]

## Constraints
* The number of nodes in the tree is in the range `[1, 104]`.
* The depth of the tree is in the range `[1, 104]`.
* `-100 <= Node.val <= 100`
* `-105 <= val <= 105`
* `1 <= depth <= the depth of tree + 1`

## 思路
使用 BFS 一層一層下去看二元樹，並使用一變數紀錄現在的 level，使用 queue 儲存每一 level 的節點，若是遇到指定層要先紀錄當下節點的子樹位置 (left, right)，新增節點之後將子樹的位置對應上新增的節點。


## 題解
### C++
使用 recursive 持續往下層搜尋，並在達到指定的深度插入新節點
```cpp
class Solution {
public:
    void travel(TreeNode* node, int depth, int ins_val, int ins_dep) {
        if(!node) return;
        if(depth == ins_dep-1) {
            TreeNode* l = new TreeNode(ins_val);
            TreeNode* r = new TreeNode(ins_val);
            l->left = node->left;
            r->right = node->right;
            node->left = l;
            node->right = r;
            return;
        }
        travel(node->left, depth+1, ins_val, ins_dep);
        travel(node->right, depth+1, ins_val, ins_dep);
    }
    TreeNode* addOneRow(TreeNode* root, int val, int depth) {
        // insert at root
        if(depth == 1) {
            TreeNode* node = new TreeNode(val);
            node->left = root;
            return node;
        }
        travel(root, 1, val, depth);
        return root;
    }
};
```

vestata:
使用 queue 去實作，使用空間去換時間，主要是 struct {TreeNode*, int} 很吃空間，但是整體速度沒有很快到非常多，時間最快到 7ms beats 95%，但是空間表現較低 beats 15%。
```cpp
class Solution {
public:
    struct NodeLevel {
        TreeNode* node;
        int level;
    };

    TreeNode* addOneRow(TreeNode* root, int val, int depth) {
        queue<NodeLevel> q;
        q.push({root, 1});
        if (depth == 1) {
            TreeNode *tmp = new TreeNode(val);
            tmp->left = root;
            return tmp;
        }

        while (!q.empty()) {
            NodeLevel front = q.front();
            q.pop();
            TreeNode *node = front.node;
            int level = front.level;

            if (node->left) {
                q.push({node->left, level + 1});
            }
            if (level + 1 == depth) {
                TreeNode *tmp = new TreeNode(val);
                tmp->left = node->left;
                node->left = tmp;
            }

            if (node->right) {
                q.push({node->right, level + 1});
            }
            if (level + 1 == depth) {
                TreeNode *tmp = new TreeNode(val);
                tmp->right = node->right;
                node->right = tmp;
            }

            if (level >= depth) break;
        }
        return root;
    }
};

```

### Python
```python
# 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
class Solution:
    def addOneRow(self, root: Optional[TreeNode], val: int, depth: int) -> Optional[TreeNode]:
        def dfs(node, depth):
            if not node: return
            if depth == 1:
                new_left = TreeNode(val)
                new_right = TreeNode(val)
                new_left.left = node.left
                node.left = new_left
                new_right.right = node.right
                node.right = new_right
                return
            else:
                dfs(node.left, depth-1)
                dfs(node.right, depth-1)

        if depth == 1:
            left = TreeNode(val)
            left.left = root
            root = left
        else:
            dfs(root, depth-1)
        return root

```