SCHOOL OF CODE BUILDERS
Learn To CODE. Become A DEVELOPER.
Pages
HOME
DATA STRUCTURES
STRINGS
ARRAYS
MATRIX
BINARY TREES
LINKED LIST
STACK
QUEUE
SORTING
SEARCHING
C
PYTHON
PSEUDOCODE
CONTEST PROBLEMS
ALGORITHMS
PATTERNS
PHP
C PUZZLES
C INTERVIEW QUESTIONS
JAVA
C++
HASHING
RECURSION
BASIC C PROGRAMS
TCS-CODEVITA
FACEBOOK
CONTACT US
Count leaf nodes in a binary tree
Count leaf nodes in a binary tree
#include
#include
struct node { int data; struct node *left,*right; }; struct node* newnode(int data) { struct node *temp=(struct node*)malloc(sizeof(struct node)); temp->data=data; temp->left=temp->right=NULL; return temp; } struct node* insert(struct node *root,int data) { if(root==NULL) return newnode(data); if(data < root->data) root->left=insert(root->left,data); else root->right=insert(root->right,data); return root; } void inorder(struct node *root) { if(root==NULL) return; inorder(root->left); printf("%d ",root->data); inorder(root->right); } int countleaves(struct node *root) { if(root==NULL) return; if(root->left==NULL && root->right==NULL) return 1; return countleaves(root->left)+countleaves(root->right); } int main(void) { struct node *root=NULL; root=insert(root,5); insert(root,3); insert(root,7); insert(root,4); insert(root,2); insert(root,1); insert(root,6); insert(root,8); //inorder(root); printf("there are %d leaf nodes in the binary tree",countleaves(root)); return 0; }
PREVIOUS
NEXT
HOME