How to find the size of the binary tree in java | Hindi coding community

0

  In last article we saw how can we print the binary tree using line by line that is level order traversal. In this article we will see how can we print the size of the binary tree. 

So here in the image you can see we have a binary tree. You have to print the size of this binary tree.

In this image we can clearly see that the size of the tree is 6 because total number of nodes in this binary tree are 6 so our output must be 6.

So now we are going to implement a Java code for this problem.

Java Code :


class Node{

int data;
Node left;
Node right;
Node(int data){
this.data=data;
this.left=null;
this.right=null;
}
}

class HindiCodingCommunity{

public static int getSize(Node root){
if(root==null){
return 0;
}
else{
return 1+ getSize(root.left)+getSize(root.right);
}
}

public static void main(String args[])
{
Node root = new Node(1);
root.left = new Node(2);
root.right= new Node(3);

root.left.left= new Node(4);
root.right.left= new Node(5);
root.right.right= new Node(6);

System.out.println(getSize(root));
}

}



Time Complexity : O(n)

Auxilary Space : O(h)






Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !