How to find sum of nodes in binary tree ,Can you change in the code
#include<bits/stdc++.h>
using namespace std;
class node {
public:
int data;
node*left;
node*right;
node(int d) {
data = d;
left = NULL;
right = NULL;
}
};
node* buildtree() {
int d;
cin>>d;
if(d==-1){
return NULL;
}
node*root = new node(d);
root->left = buildtree();
root->right = buildtree();
return root;
}
void preorder(node*root) {
if(root == NULL){
return;
}
cout<<root->data<<", ";
preorder(root->left);
preorder(root->right);
}
void inorder(node*root) {
if(root == NULL){
return;
}
inorder(root->left);
cout<<root->data<<", ";
inorder(root->right);
}
void postorder(node*root) {
if(root == NULL){
return;
}
postorder(root->left);
postorder(root->right);
cout<<root->data<<", ";
}
//Calculating height of the tree
int height(node*root) {
if(root == NULL){
return 0;
}
int ls = height(root->left);
int rs = height(root->right);
return max(ls,rs) + 1;
}
//To print a single level in a binary tree
void printkthlevel(node*root, int k ) {
if(root == NULL){
return;
}
if(k==1) {
cout<<root->data<<" ";
return;
}
printkthlevel(root->left,k-1);
printkthlevel(root->right,k-1);
return;
}
//To print all levels in a btree O(n2)
void printalllevels(node*root) {
if(root==NULL){
return;
}
int H = height(root);
for(int i=1;i<=H;i++){
printkthlevel(root,i);
cout<<endl;
}
return;
}
void bfs(node*root) {
queue<node*> que;
que.push(root);
que.push(NULL);
while(!que.empty()){
node*f = que.front();
if(f==NULL){
cout<<endl;
que.pop();
if(!que.empty()){
que.push(NULL);
}
}
else{
cout<<f->data<<" ";
que.pop();
if(f->left){
que.push(f->left);
}
if(f->right){
que.push(f->right);
}
}
}
return;
}
int count(node*root) {
if(root == NULL){
return 0;
}
return 1 + count(root->left) + count(root->right);
}
int sum(node*root){
if(root==NULL)return 0;
return root->data+sum(root->right)+sum(root->left);
}
int main(){
node*root = buildtree();
/*
preorder(root);
cout<<endl;
inorder(root);
cout<<endl;
postorder(root);
cout<<endl;
cout<<height(root);
cout<<endl;
printkthlevel(root,3);
cout<<endl;
printalllevels(root);
*/
bfs(root);
cout<<endl;
cout<<count(root)<<endl;
cout<<sum(root);
}
Can I have explanation for that
Simple recurrence relation
Sum of current node is = current_node_value + sum_of_its_children.
I will add current and rest is upto recursion to add.