Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Trees

Cousins in a Binary Tree

Easy · Trees · Asked at Amazon, Meta, Microsoft

All values are distinct. Two nodes are cousins if they are at the same depth but have different parents. Print YES if the nodes with values x and y are cousins, otherwise NO.

Input

First line: k. Second line: k values — the tree in level order, -1 means no node. Third line: x y (both values are in the tree, x ≠ y).

Output

YES or NO.

Constraints

One BFS that records each node’s depth and parent. Compare depth[x] with depth[y] and parent[x] with parent[y].

Example 1

Input

4
1 2 3 4
4 3

Output

NO

Example 2

Input

7
1 2 3 -1 4 -1 5
5 4

Output

YES

Hints

  1. Cousins need two facts: the same depth and different parents.
  2. One BFS can record both for every node.

Approach

BFS from the root, storing for each value its depth and its parent's value. Then x and y are cousins exactly when depth[x] == depth[y] and parent[x] != parent[y]. Siblings (same parent) and nodes at different depths are not cousins.

Complexity: O(n) time · O(n) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

struct Node {
    long long val;
    Node *left = nullptr, *right = nullptr;
    Node(long long v) : val(v) {}
};

Node *build(const vector<long long> &a) {
    if (a.empty() || a[0] == -1) return nullptr;
    Node *root = new Node(a[0]);
    queue<Node *> q;
    q.push(root);
    size_t i = 1;
    while (!q.empty() && i < a.size()) {
        Node *cur = q.front();
        q.pop();
        if (i < a.size() && a[i] != -1) q.push(cur->left = new Node(a[i]));
        i++;
        if (i < a.size() && a[i] != -1) q.push(cur->right = new Node(a[i]));
        i++;
    }
    return root;
}

int main() {
    int k;
    cin >> k;
    vector<long long> a(k);
    for (auto &v : a) cin >> v;
    long long x, y;
    cin >> x >> y;
    Node *root = build(a);
    unordered_map<long long, pair<int, long long>> info; // value -> (depth, parent value)
    info[root->val] = {0, 0};
    queue<Node *> q;
    q.push(root);
    while (!q.empty()) {
        Node *n = q.front();
        q.pop();
        for (Node *c : {n->left, n->right})
            if (c) {
                info[c->val] = {info[n->val].first + 1, n->val};
                q.push(c);
            }
    }
    bool cousins = info[x].first == info[y].first && info[x].second != info[y].second;
    cout << (cousins ? "YES" : "NO") << "\n";
    return 0;
}

Python solution

import sys
from collections import deque

class Node:
    __slots__ = ("val", "left", "right")

    def __init__(self, val):
        self.val, self.left, self.right = val, None, None


def build(a):
    if not a or a[0] == -1:
        return None
    root = Node(a[0])
    q = deque([root])
    i = 1
    while q and i < len(a):
        cur = q.popleft()
        if i < len(a) and a[i] != -1:
            cur.left = Node(a[i])
            q.append(cur.left)
        i += 1
        if i < len(a) and a[i] != -1:
            cur.right = Node(a[i])
            q.append(cur.right)
        i += 1
    return root


data = list(map(int, sys.stdin.read().split()))
k = data[0]
root = build(data[1 : 1 + k])
x, y = data[1 + k], data[2 + k]
info = {root.val: (0, 0)}
q = deque([root])
while q:
    node = q.popleft()
    for c in (node.left, node.right):
        if c:
            info[c.val] = (info[node.val][0] + 1, node.val)
            q.append(c)
print("YES" if info[x][0] == info[y][0] and info[x][1] != info[y][1] else "NO")

Java solution

import java.io.*;
import java.util.*;

public class Main {
    static class Node {
        long val;
        Node left, right;
        Node(long v) { val = v; }
    }

    static Node build(long[] a) {
        if (a.length == 0 || a[0] == -1) return null;
        Node root = new Node(a[0]);
        ArrayDeque<Node> q = new ArrayDeque<>();
        q.add(root);
        int i = 1;
        while (!q.isEmpty() && i < a.length) {
            Node cur = q.poll();
            if (i < a.length && a[i] != -1) q.add(cur.left = new Node(a[i]));
            i++;
            if (i < a.length && a[i] != -1) q.add(cur.right = new Node(a[i]));
            i++;
        }
        return root;
    }

    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int k = (int) in.nval;
        long[] a = new long[k];
        for (int i = 0; i < k; i++) {
            in.nextToken();
            a[i] = (long) in.nval;
        }
        in.nextToken();
        long x = (long) in.nval;
        in.nextToken();
        long y = (long) in.nval;
        Node root = build(a);
        HashMap<Long, long[]> info = new HashMap<>(); // value -> {depth, parent}
        info.put(root.val, new long[] {0, 0});
        ArrayDeque<Node> q = new ArrayDeque<>();
        q.add(root);
        while (!q.isEmpty()) {
            Node n = q.poll();
            for (Node c : new Node[] {n.left, n.right})
                if (c != null) {
                    info.put(c.val, new long[] {info.get(n.val)[0] + 1, n.val});
                    q.add(c);
                }
        }
        long[] ix = info.get(x), iy = info.get(y);
        System.out.println(ix[0] == iy[0] && ix[1] != iy[1] ? "YES" : "NO");
    }
}

Solve Cousins in a Binary Tree online · All practice problems