Computer Science, asked by Grsoul4208, 1 year ago

How to calculate number of nodes in binary tree?

Answers

Answered by Anonymous
0
====================HEYA THERE ===================



----------------  HERE IS ANSWER ------------------------

THIS IS THE FORMULA to calculate number of nodes in a binary tree 

nodes in a perfect binary tree = 2h+1 − 1



==============================




# BRAINLY2222



@ COMPUTER SCIENCE 
Answered by prathamesh1855
0
Hiya

This How To Calculate Number Of Nodes In binary tree

Size() function recursively calculates the size of a tree. It works as follows:

Size of a tree = Size of left subtree + 1 + Size of right subtree.


Here Is The Algorithm

// A recursive Java program to calculate the size of the tree

 

/* Class containing left and right child of current

   node and key value*/

class Node

{

    int data;

    Node left, right;

 

    public Node(int item)

    {

        data = item;

        left = right = null;

    }

}

 

/* Class to find size of Binary Tree */

class BinaryTree

{

    Node root;

 

    /* Given a binary tree. Print its nodes in level order

       using array for implementing queue */

    int size()

    {

        return size(root);

    }

 

    /* computes number of nodes in tree */

    int size(Node node)

    {

        if (node == null)

            return 0;

        else

            return(size(node.left) + 1 + size(node.right));

    }

 

    public static void main(String args[])

    {

        /* creating a binary tree and entering the nodes */

        BinaryTree tree = new BinaryTree();

        tree.root = new Node(1);

        tree.root.left = new Node(2);

        tree.root.right = new Node(3);

        tree.root.left.left = new Node(4);

        tree.root.left.right = new Node(5);

 

        System.out.println("The size of binary tree is : "

                            + tree.size());

    }

}




Hope it helps
Similar questions