This content originally appeared on DEV Community and was authored by Mujahida Joynab
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int val;
Node *right;
Node *left;
Node(int value)
{
this->val = value;
this->right = NULL;
this->left = 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();
Node *myLeft;
Node *myRight;
int l, r;
cin >> l >> r;
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;
}
void level_order(Node *root)
{
if (root == NULL)
{
cout << "Tree nai " << endl;
return;
}
queue<Node *> q;
q.push(root);
while (!q.empty())
{
Node *f = q.front();
q.pop();
cout << f->val << " ";
if (f->left)
q.push(f->left);
if (f->right)
q.push(f->right);
}
}
int count_nodes(Node *root)
{
if (root == NULL)
return 0;
int l = count_nodes(root->left);
int r = count_nodes(root->right);
return l + r + 1;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
Node *root = input_tree();
cout << count_nodes(root) ;
}
This content originally appeared on DEV Community and was authored by Mujahida Joynab
Print
Share
Comment
Cite
Upload
Translate
Updates
There are no updates yet.
Click the Upload button above to add an update.

APA
MLA
Mujahida Joynab | Sciencx (2025-02-13T11:50:35+00:00) Count Nodes. Retrieved from https://www.scien.cx/2025/02/13/count-nodes/
" » Count Nodes." Mujahida Joynab | Sciencx - Thursday February 13, 2025, https://www.scien.cx/2025/02/13/count-nodes/
HARVARDMujahida Joynab | Sciencx Thursday February 13, 2025 » Count Nodes., viewed ,<https://www.scien.cx/2025/02/13/count-nodes/>
VANCOUVERMujahida Joynab | Sciencx - » Count Nodes. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/02/13/count-nodes/
CHICAGO" » Count Nodes." Mujahida Joynab | Sciencx - Accessed . https://www.scien.cx/2025/02/13/count-nodes/
IEEE" » Count Nodes." Mujahida Joynab | Sciencx [Online]. Available: https://www.scien.cx/2025/02/13/count-nodes/. [Accessed: ]
rf:citation » Count Nodes | Mujahida Joynab | Sciencx | https://www.scien.cx/2025/02/13/count-nodes/ |
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.