From b5ab918a2a5f154210c617b6a2aa14ce5ea1b5c4 Mon Sep 17 00:00:00 2001 From: IndianBlitz <101599761+IndianBlitz@users.noreply.github.com> Date: Wed, 29 Jun 2022 19:41:00 +0530 Subject: [PATCH] add Count Non Leaf Nodes of Tree --- .../CPlusPlus/Trees/Count-Non-Leaf-Nodes.cpp | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 algorithms/CPlusPlus/Trees/Count-Non-Leaf-Nodes.cpp diff --git a/algorithms/CPlusPlus/Trees/Count-Non-Leaf-Nodes.cpp b/algorithms/CPlusPlus/Trees/Count-Non-Leaf-Nodes.cpp new file mode 100644 index 00000000..f584f1b0 --- /dev/null +++ b/algorithms/CPlusPlus/Trees/Count-Non-Leaf-Nodes.cpp @@ -0,0 +1,76 @@ + + +/* QUESTION-> +Given a Binary Tree of size N, your task is to complete the function countNonLeaf TreeNodes(), that should return the count of all the non-leaf TreeNodes of the given binary tree. +*/ + + + /* Prerequisites + Recursion + Post-Order Traversal + */ + + /* Complexity + Time -> O(n); + space -> O(Height of tree); + */ + + // Instructions -> just copy to run + +#include +using namespace std; + +// Basic Structure of a Tree +struct TreeNode { + int data; + struct TreeNode *left; + struct TreeNode *right; + + TreeNode(int val) { + data = val; + left = NULL; + right = NULL; + } +}; + + +//Function to calculate to count non-Leaf of Tree +int countNonLeaf ( TreeNode* root) { + if(root==NULL){ + return 0; + } + int sum=0; + + sum+= countNonLeaf(root->left); + + sum+=countNonLeaf(root->right); + + if(root->left!=NULL || root->right!=NULL){ + sum++; + } + return sum; + } + + + +int main(){ + TreeNode* root = new TreeNode(1); + root->left = new TreeNode(2); + root->right = new TreeNode(3); + root->left->left = new TreeNode(4); + root->left->right = new TreeNode(5); + root->right->right = new TreeNode(7); + + /* + 1----non leaf Node=1 + / \ + 2 3----non leaf Nodes =2 + / \ \ + 4 5 7----non leaf Nodes=0 + + Expected ans-> height=3 + */ + cout << "Count of non leaf nodes of tree is : " << countNonLeaf(root) << '\n'; + + return 0; +} \ No newline at end of file