sum of all leaf nodes of binary tree

Solutions on MaxInterview for sum of all leaf nodes of binary tree by the best coders in the world

showing results for - "sum of all leaf nodes of binary tree"
Camila
07 Feb 2018
1#include<iostream>
2using namespace std;
3struct node
4{
5  int data;
6  node* left;
7  node* right;
8};
9node* getnode(int value)
10{
11  node *temp=new node;
12  temp->data=value;
13  temp->left=NULL;
14  temp->right=NULL;
15  return temp;
16}
17node* insert_bst(node *roots,int value)
18{
19  if(roots==NULL)
20  {
21    return getnode(value);
22  }
23  if(roots->data>value)
24  {
25    roots->left=insert_bst(roots->left,value);
26  }
27  else if(roots->data<value)
28  {
29   roots->right=insert_bst(roots->right,value);
30  }
31  return roots;
32}
33int leaf_sum(node *roots)
34{
35  if(roots==NULL)
36  {
37    return 0;
38  }
39  if(roots->left==NULL&&roots->right==NULL)
40  {
41    return roots->data;
42  }
43  return (leaf_sum(roots->left)+leaf_sum(roots->right));
44}
45int main()
46{
47    node * root=new node;
48    root=NULL;
49  int value;
50  do
51  {
52    cin>>value;
53    if(value>0)
54    {
55      root=insert_bst(root,value);
56    }
57    }while(value>0);
58    //Inorder(root);
59   cout<<"Sum of all leaf nodes are "<<leaf_sum(root);
60  return 0;
61}
62