১৮-৫ঃ Count Number of Nodes of a Binary Tree
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int val;
Node *left;
Node *right;
Node(int val)
{
this->val = val;
this->left = NULL;
this->right = NULL;
}
};
// বাইনারী ট্রি ইনপুট নেয়ার কোড যা গত পেজে ব্যাখ্যা করা হয়েছে।
Node *input_tree()
{
int val;
cin >> val;
Node *root;
if (val == -1)
root = NULL;
else
root = new Node(val);
queue<Node *> q;
if (root)
q.push(root);
while (!q.empty())
{
Node *p = q.front();
q.pop();
int l, r;
cin >> l >> r;
Node *myLeft;
Node *myRight;
if (l == -1)
myLeft = NULL;
else
myLeft = new Node(l);
if (r == -1)
myRight = NULL;
else
myRight = new Node(r);
p->left = myLeft;
p->right = myRight;
if (p->left)
q.push(p->left);
if (p->right)
q.push(p->right);
}
return root;
}
// ফাংশনটিতে প্যারামিটার হিসেবে কোনো একটি Binary Tree এর Root দিলে তাতে কয়টি Node আছে তা বলে দেয়
int count(Node *root)
{
if (root == NULL) // যদি Root Null হয় তবে Tree টিতে কোনো Node নেই
return 0;
int l = count(root->left); // Left subtree তে কয়টি Node আছে তা count ফাংশনের মাধ্যমে কাউন্ট করা হচ্ছে
// এই ক্ষেত্রে Left subtree এর Root হলো current root Node এর left child
int r = count(root->right);// Right subtree তে কয়টি Node আছে তা count ফাংশনের মাধ্যমে কাউন্ট করা হচ্ছে
// এই ক্ষেত্রে Right subtree এর Root হলো current root Node এর right child
return l + r + 1; // left subtree এবং right subtree এর Node সংখ্যার সাথে Root node এর কাউন্ট ১ যোগ করে রিটার্ন করা হচ্ছে
}
int main()
{
Node *root = input_tree();
cout << count(root) << endl;
return 0;
}Last updated