From 6613ddbbfa4593fb318a91bb85c6cc42e7be9a45 Mon Sep 17 00:00:00 2001 From: Amandeep Singh <47387270+Amandeepanmol@users.noreply.github.com> Date: Sat, 23 Oct 2021 23:27:51 +0530 Subject: [PATCH] Create leaf sum binary tree.cpp --- leaf sum binary tree.cpp | 48 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 leaf sum binary tree.cpp diff --git a/leaf sum binary tree.cpp b/leaf sum binary tree.cpp new file mode 100644 index 0000000..4ea0d44 --- /dev/null +++ b/leaf sum binary tree.cpp @@ -0,0 +1,48 @@ +#include +using namespace std; + +struct Node +{ + int data; + Node *left,*right; + + public: + Node(int key) + { + data=key; + left=right=NULL; + } +}; + +int leaf_traversal(Node *root) // using preorder traveral +{ + if(root==NULL) + { + return 0; + } + int sum=0; + if(root->left==NULL && root->right==NULL) + { + sum+= root->data; + } + + return sum+leaf_traversal(root->left)+leaf_traversal(root->right); +} + + + +int main() +{ + struct Node* root=new Node(10); + root->left=new Node(20); + root->right=new Node(30); + root->right->left=new Node(40); + root->right->right=new Node(50); + root->right->right->left=new Node(11); + + + cout<