मुख्य कंटेंट तक स्किप करें

Cousins in Binary Tree

KANISHKA GUPTA
EditReport

Cousins in Binary Tree

Problem Description

Given the root of a binary tree with unique values and the values of two different nodes of the tree, x and y, return true if the nodes corresponding to the values x and y in the tree are cousins, or false otherwise.

Two nodes of a binary tree are considered cousins if they have the same depth but different parents.

Note that in a binary tree, the root node is at depth 0, and children of each depth k node are at depth k + 1.

Video Explanation

Approach

To determine if two nodes are cousins, we can use a Breadth-First Search (BFS) approach. We will traverse the tree level by level while keeping track of the parent of each node and their respective depths.

Steps:

  1. Initialization: Use a queue to facilitate the BFS traversal. Store each node along with its parent and depth.

  2. BFS Traversal:

    • Dequeue each node from the front of the queue.
    • If the current node has children, enqueue them along with their parent and the incremented depth.
    • Check if both x and y are found at the same depth but with different parents.
  3. Return Result:

    • If both nodes are found to be cousins during the traversal, return true.
    • If the traversal ends without finding them, return false.

Solutions

class Solution {
public:
bool isCousins(TreeNode* root, int x, int y) {
int xDepth = -1, yDepth = -1;
TreeNode *xParent = nullptr, *yParent = nullptr;

function<void(TreeNode*, TreeNode*, int)> dfs = [&](TreeNode* node, TreeNode* parent, int depth) {
if (!node) return;
if (node->val == x) { xParent = parent; xDepth = depth; }
if (node->val == y) { yParent = parent; yDepth = depth; }
dfs(node->left, node, depth + 1);
dfs(node->right, node, depth + 1);
};

dfs(root, nullptr, 0);
return xDepth == yDepth && xParent != yParent;
}
};
Track Your Progress

Done with this topic? Mark it as complete to track your progress.

💬 Discuss this page

Have a question or spot something confusing in "Cousins in Binary Tree"? Ask below — it's backed by GitHub Discussions, so maintainers get notified like any other GitHub activity.