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

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;


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


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