Easy C++ Solution with O(N) time complexity and constant space Complexity


#1
TreeNode* get(TreeNode *root1, TreeNode* root2){
    if(!root1 && !root2) return NULL;
    if(root1 && !root2) return root1;
    if(!root1 && root2) return root2;
    root1->val += root2->val;
    root1->left = get(root1->left,root2->left);
    root1->right = get(root1->right,root2->right);
    return root1;
}
TreeNode* Solution::solve(TreeNode* A, TreeNode* B) {
    TreeNode *ans = get(A,B);
    return ans;
}

#2

Your code isn’t constant space, recursive code occupy space over the function call stack.


#3

You are right Naman, but in interview usually recursive code stack is not considered in space complexity