Link
https://leetcode.com/problems/add-one-row-to-tree/description/
Solution
首先,处理特殊情况:若d == 1,新添加的节点将成为根结点
然后,对于一般情况:dfs到d - 1层,根据要求添加节点即可
Code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void addOneRowHelper(TreeNode* root, int v, int d, int dep) {
if (d - 1 == dep) {
TreeNode* leftNode = root->left;
TreeNode* rightNode = root->right;
root->left = new TreeNode(v);
root->right = new TreeNode(v);
root->left->left = leftNode;
root->right->right = rightNode;
} else {
if (root->left) addOneRowHelper(root->left, v, d, dep + 1);
if (root->right) addOneRowHelper(root->right, v, d, dep + 1);
}
}
TreeNode* addOneRow(TreeNode* root, int v, int d) {
if (d == 1) {
TreeNode* newRoot = new TreeNode(v);
newRoot->left = root;
return newRoot;
}
addOneRowHelper(root, v, d, 1);
return root;
}
};