https://leetcode.com/problems/add-one-row-to-tree/description/
class Solution {
public:
TreeNode* addOneRow(TreeNode* root, int v, int d) {
if (d == 1) {
TreeNode* ret = new TreeNode(v);
ret->left = root;
return ret;
}
queue< pair<TreeNode*, int> > q;
q.push( make_pair(root, 2) );
while (!q.empty()) {
pair<TreeNode*, int> tp = q.front();
q.pop();
if (tp.second == d) {
TreeNode* tmp = tp.first->left;
tp.first->left = new TreeNode(v);
tp.first->left->left = tmp;
tmp = tp.first->right;
tp.first->right = new TreeNode(v);
tp.first->right->right = tmp;
continue;
}
if (tp.second + 1 <= d) {
if (tp.first->left) {
q.push( make_pair(tp.first->left, tp.second + 1) );
}
if (tp.first->right) {
q.push( make_pair(tp.first->right, tp.second + 1) );
}
}
}
return root;
}
};