Find total nodes and sum of all nodes of a binary tree (Recursive)
#include <bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) :
val(x), left(left), right(right) {}
};
TreeNode *BuildTree()
{
int d;
cin >> d;
if (d == -1)
return NULL;
TreeNode *Node = new TreeNode(d);
Node->left = BuildTree();
Node->right = BuildTree();
return Node;
}
void print(TreeNode *root)
{
if (root == NULL)
return;
cout << root->val;
print(root->left);
print(root->right);
}
int totalNodes(TreeNode *root)
{
if (root == NULL)
return 0;
return 1 + totalNodes(root->left) + totalNodes(root->right);
}
int sumOfNodes(TreeNode *root)
{
if (root == NULL)
return 0;
return root->val + sumOfNodes(root->left) +
sumOfNodes(root->right);
}
int main()
{
TreeNode *root = BuildTree();
cout << "PreOrder of Tree is: ";
print(root);
cout << endl;
cout << "Total nodes in binary tree : "
<< totalNodes(root) << endl;
cout << "Total sum of all nodes will be: "
<< sumOfNodes(root);
}

Comments
Post a Comment