c++浅拷贝与深拷贝(LeetCode669)

LeetCode题目传送门

c++的指针变量需要首先赋值，否则会变成野指针。类似这种应该都报错，因为

class Solution {
public:
bool dfs(TreeNode* root, int L, int R, TreeNode * ans){//浅拷贝，指针引用！
ans->left = ans->right = NULL;

bool zy = false;
bool h;
if (root->val >= L && root->val <= R){
ans->val = root->val;
zy = true;
}
if (root->left != NULL){
TreeNode* lll = (TreeNode*)(malloc(sizeof(TreeNode)));
lll->left = lll->right = NULL;//指针初始化，拒绝野指针

h = dfs(root->left, L, R, lll);
if (h){//判断坐标子树上有没有东西，有东西的话就把
if (root->val >= L && root->val <= R){
//ans->left = (TreeNode*)(malloc(sizeof(TreeNode)));
ans->left = lll;
}
else{
//ans = lll;
ans->val = lll->val;
ans->left = lll->left;
ans->right = lll->right;
}
}
zy |= h;
}
if (root->right){
TreeNode* rrr = (TreeNode*)(malloc(sizeof(TreeNode)));
rrr->left = rrr->right = NULL;
h = dfs(root->right, L, R, rrr);
if (h){
if (root->val >= L && root->val <= R){
//ans->right = (TreeNode*)(malloc(sizeof(TreeNode)));
ans->right = rrr;
}
else{
ans->val = rrr->val;
ans->left = rrr->left;
ans->right = rrr->right;
}
}
zy |= h;
}
return zy;
}
TreeNode* trimBST(TreeNode* root, int L, int R) {
cout << sizeof(TreeNode) << endl;
TreeNode* res = (TreeNode*)(malloc(sizeof(TreeNode)));
res->left = res->right = NULL;//指针初始化，拒绝野指针
dfs(root, L, R, res);
return res;
}
};


bool dfs(TreeNode* root, int L, int R, TreeNode *& ans)

• 当root的值位于L和R之间，则递归修剪其左右子树，返回root。
• 当root的值小于L，则其左子树的值都小于L，抛弃左子树，返回修剪过的右子树。
• 当root的值大于R，则其右子树的值都大于R，抛弃右子树，返回修剪过的左子树。

public TreeNode trimBST(TreeNode root, int L, int R) {
if (root == null) return null;
if (root.val < L){
return trimBST(root.right, L, R);
}
else if (root.val > R){
return trimBST(root.left, L, R);
}
else {
TreeNode ans = new TreeNode(root.val);
ans.left = trimBST(root.left, L, R);
ans.right = trimBST(root.right, L, R);
return ans;
}
}


posted @ 2017-09-14 15:28  ohazyi  阅读(...)  评论(...编辑  收藏