Thursday, June 8, 2017

Program to Calculate Size of a Binary tree

Number of nodes available in a tree will be called size of tree. Below is the recursive program to calculate size of a binary tree.
       

package dataStructure.tree;

public class SizeOfTree {

 public static void main(String[] args) {
  
  Node rL = new Node(null, 5, null);
  Node rR = new Node(null, 15, null);
  Node root = new Node(rL, 10, rR);
  
  System.out.println(sizeOfTree(root));
 }
 
 public static int sizeOfTree(Node root){
  if(null == root){
   return 0;
  }
  return sizeOfTree(root.left) + 1 + sizeOfTree(root.right);
 }
 private static class Node{
  @SuppressWarnings("unused")
  public int key;
  public Node left;
  public Node right;
  /**
   * @param key
   * @param left
   * @param right
   */
  public Node(Node left, int key, Node right) {
   this.key = key;
   this.left = left;
   this.right = right;
  }
 }

}

        
 

No comments:

Post a Comment