Why do multiple functions use less memory than one large function with multiple variables

Viewed 52

I was doing a Leetcode challenge and my code used about .5 kb of memory more than other submissions that looked more complex. The challenge itself was inverting a binary tree. Although I submitted my solution multiple times to take the average values of runtime and memory usage for my code.
My code below runs on average for 3ms and takes 8.5 kb of memory after 10 trial submissions.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
       if(root == nullptr) return root;
     
       invertTree(root -> left);
       invertTree(root -> right);
        
       TreeNode* tmp = root ->left;
        root -> left = root -> right;
        root -> right = tmp;
        return root;

    }
};

The code below is the sample submission that Leetcode shows as an example of 0ms runtime and 8kb of memory usage

class Solution {
public:
    void invert(TreeNode* root)
    {
        if(root==nullptr)
            return;
        invert(root->left);
        invert(root->right);
        TreeNode* temp = root->right;
        root->right = root->left;
        root->left = temp;
    }
    TreeNode* invertTree(TreeNode* root) {
        if(root==nullptr)
            return nullptr;
        invert(root);
        return root;
    }
};

I am wondering how the code given uses two functions and uses less memory than my solution? Additionally, I am relatively new to programming, and am wondering if this case is exemplary of deeper mechanic within the C++ language or too nitpick-y to warrant any concern. Thanks for reading

0 Answers
Related