考察点:递归, 二叉树;
思路:递归思想;很重要的是help函数的处理,它要返回指针,而且它的功能是返回最终的root,这个root是满足条件的root。当然,help函数里还要递归,确定好为NULL的条件和depth==curdepth这两个结束条件就ok了。
C++代码:
/**
* 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:
TreeNode* addOneRow(TreeNode* root, int v, int d) {
if (d == 1) {
TreeNode * ret = new TreeNode(v);
ret->left = root;
return ret;
}
return addOneRow(root, v, d, 1);
}
TreeNode* addOneRow(TreeNode* root, int v, int d, int curDepth) {
if (root == NULL)
return NULL;
if (d == curDepth + 1) {
TreeNode* tempLeft = root->left;
TreeNode* tempRight = root->right;
TreeNode * newLeft = new TreeNode(v);
TreeNode * newRight = new TreeNode(v);
root->left = newLeft;
root->right = newRight;
newLeft->left = tempLeft;
newRight->right = tempRight;
return root;
} else {
addOneRow(root->left, v, d, curDepth+1);
addOneRow(root->right, v, d, curDepth+1);
}
return root;
}
};