Leetcode: Cousins in Binary Tree
My first issue is that this function is badly named.

    void is_cousins(TreeNode* root, int to_find, int depth, 
        TreeNode* parent, pair&lt;int, TreeNode*&gt;&amp; pair)


It has nothing to do with cousins. It is simply finding the depth and parent of a particular value. You should name it appropriateely.



I don't like passing output parameters to a function:

    void is_cousins(TreeNode* root, int to_find, int depth, 
        TreeNode* parent, pair&lt;int, TreeNode*&gt;&amp; pair)


The parameter pair is the output of the function. Why not just return this value. That would be more logical and easier to read.



You don't have a truth state on whether the value x or y are found. I suppose you could say that nullptr in pair is a good way to test this. But that will make things complicated down the road when you try and use this function for other things that are not cousin related; so I don't like that idea. You could used a depth of -1 to indicate failure that would be better.

Talking of default values:

Your current default result is make_pair(0, nullptr) this means you found the root as the value (even if the root value does not equal left of right). This may work for your current situation out of sheer luck but you are returning a bad value.

i.e. A value that is not found in the tree and the root node will both return the same result.



Here is a major ineffeciency.

    is_cousins(root-&gt;left, to_find, depth + 1, root, pair);
    is_cousins(root-&gt;right, to_find, depth + 1, root, pair);


If you find the value on the left you still search the right subtree. This means you always search the whole tree even if you find the correct node very quickly.

You should check the result of the left search before doing the right search.



This is an anti patten

        if (pairx.first == pairy.first &amp;&amp; pairx.second != pairy.second)
            return true;
        return false;


The pattern:

        if (test) {
            return true;
        }
        return false;

        // Can always be simplified to:

        return test;


This is a long handed way of writing:

         return pairx.first == pairy.first &amp;&amp; pairx.second != pairy.second;


If you think that is too long for an expression to use in a reurn, then it is too long an expression for any context. In that case you should put the test in a named function so it is obvious what it is doing.

          return are_cousing_nodes_from_Depth(pairx, pairy);

     using DepthInfo = pair&lt;int, TreeNode*&gt;;
     inline bool are_cousing_nodes_from_Depth(DepthInfo const&amp; lhs, DepthInfo const&amp; rhs)
     {
         return lhs.first  == rhs.first    // Same depth
             &amp;&amp; lhs.second != rhs.second;  // Not siblings
     }