কম্পিউটার টিউটোরিয়াল

C++-এ বাইনারি ট্রিতে দেওয়া নোডের কজন (Cousins) প্রিন্ট করুন

বাইনারি ট্রিতে দুটি নোড কজন (cousins) হলে যদি তারা একই লেভেলে (depth) থাকে কিন্তু প্যারেন্ট ভিন্ন হয়। এক নোড দেওয়া আছে, তার কজন নোডগুলো প্রিন্ট করতে হবে (সিবলিং বাদ দিয়ে)।

উদাহরণ: ট্রিতে নোড ৮-এর কজন: ৩, ৭।

দুটি ধাপ
  1. নোডটির লেভেল বের করুন (রুট লেভেল ১)।
  2. সেই লেভেলের সব নোড প্রিন্ট করুন, শুধু দিয়ে যাওয়া নোড এবং তার সিবলিং বাদ দিয়ে।
উদাহরণ কোড
#include <bits/stdc++.h>
using namespace std;

struct Node { int data; Node *left, *right; };

Node* newNode(int item) {
    Node* temp = new Node;
    temp->data = item;
    temp->left = temp->right = NULL;
    return temp;
}

int levelOfNode(Node* root, Node* node, int level) {
    if (root == NULL) return 0;
    if (root == node) return level;
    int downlevel = levelOfNode(root->left, node, level + 1);
    if (downlevel != 0) return downlevel;
    return levelOfNode(root->right, node, level + 1);
}

void printCousin(Node* root, Node* node, int level) {
    if (root == NULL || level < 2) return;
    if (level == 2) {
        if (root->left == node || root->right == node) return;
        if (root->left) cout << root->left->data << " ";
        if (root->right) cout << root->right->data;
    } else if (level > 2) {
        printCousin(root->left, node, level - 1);
        printCousin(root->right, node, level - 1);
    }
}

void cousinNode(Node* root, Node* node) {
    int level = levelOfNode(root, node, 1);
    printCousin(root, node, level);
}

int main() {
    Node* root = newNode(11);
    root->left = newNode(15);
    root->right = newNode(4);
    root->left->left = newNode(3);
    root->left->right = newNode(7);
    root->left->right->right = newNode(9);
    root->right->left = newNode(17);
    root->right->right = newNode(8);
    root->right->left->right = newNode(5);
    cout << "The cousin nodes are : \t";
    cousinNode(root, root->right->right);
    return 0;
}
আউটপুট
The cousin nodes are : 3 7
  1. C++-এ বাইনারি ট্রির সব ইন্টারনাল নোড প্রিন্ট করা

  2. C++-এ বাইনারি ট্রিতে K-সম পাথ প্রিন্ট করা

  3. C++-এ একটি নির্দিষ্ট নোড থেকে দূরত্ব k-এ থাকা সব নোড প্রিন্ট করা

  4. বাইনারি ট্রিতে রুট থেকে নির্দিষ্ট নোডের দূরত্ব বের করা C++-তে