Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<queue>
- using namespace std;
- class Node{
- public:
- int data;
- Node *left,*right;
- Node(int key){
- data=key;
- left=NULL;
- right=NULL;
- }
- };
- int CountLeaves(Node *root){
- if(root==NULL)
- return 0;
- int count=0;
- queue<Node *>q;
- q.push(root);
- while(!q.empty()){
- Node *temp=q.front();
- q.pop();
- if(temp->left==NULL && temp->right==NULL)
- count++;
- if(temp->left!=NULL)
- q.push(temp->left);
- if(temp->right!=NULL)
- q.push(temp->right);
- }
- return count;
- }
- int CountFullNodes(Node *root){
- if(root==NULL)
- return 0;
- int count=0;
- queue<Node *>q;
- q.push(root);
- while(!q.empty()){
- Node *temp=q.front();
- q.pop();
- if(temp->left!=NULL && temp->right!=NULL)
- count++;
- if(temp->left!=NULL)
- q.push(temp->left);
- if(temp->right!=NULL)
- q.push(temp->right);
- }
- return count;
- }
- int CountNodes(Node *root){
- if(root==NULL)
- return 0;
- int count=0;
- queue<Node *>q;
- q.push(root);
- while(!q.empty()){
- Node *temp=q.front();
- q.pop();
- count++;
- if(temp->left!=NULL)
- q.push(temp->left);
- if(temp->right!=NULL)
- q.push(temp->right);
- }
- return count;
- }
- int CountHalfNodes(Node *root){ //by using previous functions(CountLeaves,CountFull)
- if(root==NULL)
- return 0;
- int total= CountNodes(root);
- int full= CountFullNodes(root);
- int leaves= CountLeaves(root);
- return total-full-leaves;
- }
- int countHalfNodes(Node *root){ //without using previous functions
- if(root==NULL)
- return 0;
- int count=0;
- queue<Node *>q;
- q.push(root);
- while(!q.empty()){
- Node *temp=q.front();
- q.pop();
- if((temp->left==NULL &&temp->right!=NULL) ||(temp->right ==NULL && temp->left !=NULL))
- count++;
- if(temp->left!=NULL)
- q.push(temp->left);
- if(temp->right!=NULL)
- q.push(temp->right);
- }
- return count;
- }
- int main(){
- Node *root=NULL;
- Node *newnode=new Node(1);
- root=newnode;
- root->left=new Node(2);
- root->right=new Node(3);
- (root->left)->left=new Node(4);
- (root->right)->right=new Node(5);
- (root->right)->left=new Node(7);
- cout<<CountHalfNodes(root);
- cout<<endl<<countHalfNodes(root);
- return 0;
- }
Add Comment
Please, Sign In to add comment