4
\$\begingroup\$

Cousins are nodes at the same level of the tree, with different parents. They don't have to share the same grandparent.

My solution depends on having a binary search tree with unique elements.

This code is faster than writing a special find(Node *) that returns the node's level and parent, and comparing results for each node. If the nodes are not at the same level, this version will only descend down to the level of the node closer to the top, and bail out early.

I'm looking for confirmation that it is correct.

bool are_cousins(Node *root, Node *a, Node *b)
{
 if (a == b || a == nullptr || b == nullptr) {
 return false;
 }
 Node *a_parent = nullptr;
 Node *b_parent = nullptr;
 Node *a_seek = root;
 Node *b_seek = root;
 while (a_seek != nullptr && b_seek != nullptr) {
 if (a == a_seek && b == b_seek) {
 // found both nodes at the same level
 return a_parent != b_parent;
 }
 if (a == a_seek || b == b_seek) {
 // found one node but not the other at this level. bail out
 return false;
 }
 // found neither. seek down one more level
 a_parent = a_seek;
 a_seek = (a->value < a_seek->value) ?
 a_seek->left : a_seek->right;
 b_parent = b_seek;
 b_seek = (b->value < b_seek->value) ?
 b_seek->left : b_seek->right;
 }
 return false;
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Sep 12, 2014 at 3:20
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

The logic seems sane to me in general.

If the caller has the values to seek instead of node pointers, then you could change the function parameters to the value types and drop the a == nullptr || b == nullptr checks. But if the caller has node pointers that you cannot know for sure if null or not, then indeed you don't have a choice.

I find these statements more readable without the line breaks and unnecessary parentheses:

a_seek = a->value < a_seek->value ? a_seek->left : a_seek->right;
b_seek = b->value < b_seek->value ? b_seek->left : b_seek->right;
answered Sep 12, 2014 at 3:36
\$\endgroup\$
2
  • \$\begingroup\$ a and a_seek are pointers, so we're only comparing the addresses. This function searches for specific nodes instead of values. You're right, the function could take values instead of node pointers instead, but the fundamental logic would not change. \$\endgroup\$ Commented Sep 12, 2014 at 3:40
  • \$\begingroup\$ You have a point. I rewrote that part. \$\endgroup\$ Commented Sep 12, 2014 at 4:09

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.