Sunday, August 19, 2012

Count the number of leaf nodes in Binary Tree and Print the leaf nodes



package com.test;

public class BinaryTree {

 public static void main(String args[]){
 
    // Tree root node.
       int rootValue = 5;
       TreeNode rootnode = new TreeNode(rootValue);
       System.out.println("root node created. " + rootnode.nodeValue);
     
       // Inserting elements into binary tree
       insertion(rootnode, 3);
       insertion(rootnode, 7);
       insertion(rootnode, 1);
       insertion(rootnode, 4);
       insertion(rootnode, 6);
       insertion(rootnode, 8);
       
       System.out.println("Binary Tree");

       printTree(rootnode);

      System.out.println("Number of leaf nodes"+printLeafNodes(rootnode));
    
   }

// Counting and Printing the number of leaf nodes
  private static int printLeafNodes(TreeNode rootnode) {

  if(rootnode==null)
  return 0;
 if(rootnode.leftReference==null && rootnode.rightReference==null)
  {
  System.out.println(rootnode.nodeValue);
  return 1;
  }
 return printLeafNodes(rootnode.leftReference) + printLeafNodes(rootnode.rightReference);   
}

     
  // Printing Tree contents
   public static void printTree(TreeNode node) {
       if (node != null) {
           printTree(node.leftReference);
           System.out.println("Node" + node.nodeValue);
           printTree(node.rightReference);
       }
   }
}

No comments:

Post a Comment

Thanks for your valuable comments