Mu solution to Leetcode problem Cousins in Binary Tree works, but the code feels bulky. Is there a better way to solve this problem, particularly to use less additional variables? I will appreciate any suggestions on how to improve this code.
Problem:
In a binary tree, the
root
node is at depth0
, and children of each depthk
node are at depthk+1
.Two nodes of a binary tree are cousins if they have the same depth, but have different parents.
We are given the
root
of a binary tree with unique values, and the valuesx
andy
of two different nodes in the tree.Return
true
if and only if the nodes corresponding to the valuesx
andy
are cousins.
My code:
/** * 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 { private: void is_cousins(TreeNode* root, int to_find, int depth, TreeNode* parent, pair<int, TreeNode*>& pair) { if (!root) return; is_cousins(root->left, to_find, depth + 1, root, pair); is_cousins(root->right, to_find, depth + 1, root, pair); if (root->val == to_find) { pair.first = depth; pair.second = parent; return; } } public: bool isCousins(TreeNode* root, int x, int y) { pair<int, TreeNode*> pairx = make_pair(0, nullptr); pair<int, TreeNode*> pairy = make_pair(0, nullptr); is_cousins(root, x, 0, nullptr, pairx); is_cousins(root, y, 0, nullptr, pairy); if (pairx.first == pairy.first && pairx.second != pairy.second) return true; return false; } };
additional variables
. The second wouldn't enter my mind; but seems about as valid as single assignment.\$\endgroup\$