The question is Leetcode 814. Binary Tree Pruning. Once I passed pointer to the root and then pointer to the address of root. root is also the address, that's why I tried to directly assign it to nullptr in first case. why I cannot do this? How the 1st code is different from 2nd?
1.
class Solution {
public:
void prune(TreeNode *root){
if(!root) return;
prune(root->left);
prune(root->right);
if(root->val==0 && (!root->left && !root->right)){
root = nullptr; //why root is not getting assigned here?
}
}
TreeNode* pruneTree(TreeNode* root) {
prune(root);
return root;
}
};
class Solution {
public:
void prune(TreeNode *&root){
if(!root) return;
prune(root->left);
prune(root->right);
if(root->val==0 && (!root->left && !root->right)){
root = nullptr;
}
}
TreeNode* pruneTree(TreeNode* root) {
prune(root);
return root;
}
};
I tried but couldn't understand, please someone help. Thank you!!