Give an algorithm for finding the number of nodes in a binary tree recursively

package in.blogspot.arunj2ee.ds.tree.binary.que;

import in.blogspot.arunj2ee.ds.tree.BinaryTreeNode;
import in.blogspot.arunj2ee.ds.tree.util.BTreePrinter;
import in.blogspot.arunj2ee.ds.tree.util.TreeUtil;

/**
 * Que: Give an algorithm for finding the number of nodes in a binary tree recursively
 * Time Complexity: O(n), Space Complexity: O(n)
 *
 * @author Arun.Singh
 *
 */
public class Que6 {
public static int size(BinaryTreeNode root){

if(root == null)
return 0;

int leftCount = (root.getLeft() == null) ? 0 : size(root.getLeft());
int rightCount = (root.getRight() == null) ? 0 : size(root.getRight());

return leftCount + rightCount + 1;
}

public static void main(String []args){
BinaryTreeNode rootNode = TreeUtil.createRandomBinaryTree();
BTreePrinter.printBinaryTreeNode(rootNode);
System.out.println("Number of nodes in tree: " + size(rootNode));
}

}
========================================================================
Refer Core Classes: http://arunj2ee.blogspot.in/2017/05/tree-core-and-utility-classes.html
========================================================================
Share on Google Plus

About Admin

Arun is a JAVA/J2EE developer and passionate about coding and managing technical team.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment