Give an algorithm for finding the number of nodes in a binary tree non-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;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Que: Give an algorithm for finding the number of nodes in a binary tree non-recursively
 * Time Complexity: O(n), Space Complexity: O(n)
 *
 * @author Arun.Singh
 *
 */
public class Que7 {
public static int size(BinaryTreeNode root){
int nodeCount = 0;
if(root == null)
return nodeCount;

Queue<BinaryTreeNode> q = new LinkedList<BinaryTreeNode>();
q.offer(root);

while(!q.isEmpty()){
BinaryTreeNode tmp = q.poll();
if(tmp != null)
nodeCount++;

if(tmp.getLeft() != null)
q.add(tmp.getLeft());

if(tmp.getRight() != null)
q.add(tmp.getRight());
}
return nodeCount;
}

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